mysql的多表连接查询

mysql的多表连接查询

1.建库建表
(1)创建数据库mydb11_stu并使用数据库

create database mydb11_stu; use mydb11_stu;

(2)创建student表

create table student( id int(10) not NULL unique primary key, name varchar(20) not NULL, sex varchar(4), birth year, department varchar(20), address varchar(50));

(3)创建score表

create table score( id int (10) not null unique primary key auto_increment, stu_id int(10) not null, c_name varchar(20), grade int(10));

2.插入数据

(1)向student表插入记录如下:

insert into student values (901,'张三丰','男',2002,'计算机系','北京市海淀区'), (902,'周全有','男',2000,'中文系','北京市昌平区'), (903,'张思维','女',2003,'中文系','湖南省永州市'), (904,'李广昌','男',1999,'英语系','辽宁省皋新市'), (905,'王翰','男',2004,'英语系','福建省厦门市'), (906,'王心凌','女',1998,'计算机系','湖南省衡阳市');

(2)向score表插入记录如下:

insert into score values (null,901,'计算机',98), (null,901,'英语',80), (null,902,'计算机',65), (null,902,'中文',88), (null,903,'中文',95), (null,904,'计算机',70), (null,904,'英语',92), (null,905,'英语',94), (null,906,'计算机',49), (null,906,'英语',83);

3.查询
(1).分别查询student表和score表的所有记录

select * from student;

select * from score;


(2).查询student表的第2条到5条记录

select * from student limit 1,4;


(3).从student表中查询计算机系和英语系的学生的信息

select * from student where department in('计算机系','英语系');


(4).从student表中查询年龄小于22岁的学生信息

select *,year(now())-birth '年龄' from student where year(now())-birth<22;


(5).从student表中查询每个院系有多少人

select department '院系',count(id) '人数' from student group by department;


(6).从score表中查询每个科目的最高分

select c_name '科目名称',max(grade) '最高分' from score group by c_name;


(7).查询李广昌的考试科目(c_name)和考试成绩(grade)

select name '姓名',c_name '考试科目',grade '考试成绩' from student join score on student.id=score.stu_id where name='李广昌';


(8).用连接的方式查询所有学生的信息和考试信息

select student.*,score.c_name,score.grade from student join score on student.id=score.stu_id;


(9).计算每个学生的总成绩

select name '姓名',sum(grade) '总成绩' from student join score on student.id=score.stu_id group by student.id;


(10).计算每个考试科目的平均成绩

select c_name '考试科目',round(avg(grade),2) '平均成绩' from student join score on student.id=score.stu_id group by c_name;


(11).查询计算机成绩低于95的学生信息

select student.*,grade from student join score on student.id=score.stu_id where c_name='计算机' and grade<95;


(12).将计算机考试成绩按从高到低进行排序

select name '姓名',c_name '科目',grade '成绩' from student join score on student.id=score.stu_id where c_name='计算机' order by grade descc;


(13).从student表和score表中查询出学生的学号,然后合并查询结果

select id from student union select stu_id from score;


(14).查询姓张或者姓王的同学的姓名、院系和考试科目及成绩

select name '姓名',department '院系',c_name '考试科目',grade '成绩' from student join score on student.id=score.stu_id where name like '张%' or name like '王%';


(15).查询都是湖南的学生的姓名、年龄、院系和考试科目及成绩

select name '姓名',year(now())-birth '年龄',department '院系',c_name '考试科目',grade '成绩' from student join score on student.id=score.stu_idtu_id where address like '湖南省%';