数据库
首页 > 数据库> > mysql多表查询练习

mysql多表查询练习

作者:互联网

导入hellodb.sql生成数据库,并进入到数据库之中

mysql -uroot < hellodb.sql
use mysql

(1)以ClassID分组,显示每班的同学的人数
`select classid,count(stuid) from students group by classid``
mysql多表查询练习
(2)以Gender分组,显示其年龄之和
select gender,sum(age) from students group by gender
mysql多表查询练习
(3)以ClassID分组,显示其平均年龄大于25的班级
select classid,avg(age) as new_age from students group by classid having new_age>25
mysql多表查询练习
(4)以Gender分组,显示各组中年龄大于25的学员的年龄之和
select gender,sum(age) from students group by gender
mysql多表查询练习
(5)显示前5位同学的姓名、课程及成绩
select name,course,score from (select name,score,courseid from (select * from students where stuid<=5) as s inner join scores on scores.stuid=s.stuid)as t inner join courses on courses.courseid=t.courseid

(6)显示其成绩高于80的同学的名称及课程
select name,course from (select name,score,courseid from (select from scores where Score>80) as t inner join students on students.stuid=t.stuid) as t inner join courses on courses.courseid=t.courseid
mysql多表查询练习
(7)求前8位同学每位同学自己两门课的平均成绩,并按降序排列
select t.stuid,avg(score) from (select stuid,courseid from (select
from students where stuid<=8) as s inner join coc on s.classid=coc.classid) as t inner join scores on s cores.stuid=t.stuid group by t.stuid
mysql多表查询练习
(8)取每位同学各门课的平均成绩,显示成绩前三名的同学的姓名和平均成绩
select name,avg(score) as 平均分数 from (select name,courseid from students inner join coc on students.classid=coc.classid) as s inner join scores on s.courseid=scores.courseid group by stuid order by 平均分数 desc limit 3
mysql多表查询练习
(9)显示每门课程课程名称及学习了这门课的同学的个数
select courseid,count(CourseID) from students inner join coc on coc.classid=students.classid group by courseid

(10)显示其年龄大于平均年龄的同学的名字
select * from students where age>(select avg(age) from students)

(11)显示其学习的课程为第1、2,4或第7门课的同学的名字
select name,courseid from (select * from coc where CourseIDin ('1','2','4','7')) as new inner join students on students.classid=new.classid

(12)显示其成员数最少为3个的班级的同学中年龄大于同班同学平均年龄的同学
select * from (select name,classid,age from students) as s inner join (select new.classid,avg(age) as cc from (select classid from students group by ClassID having count(stuid) >= 3) as new inner join students on students.classid=new.classid group by new.classid) as a on a.classid=s.classid where cc<age;

标签:classid,多表,students,age,查询,courseid,mysql,stuid,select
来源: https://blog.51cto.com/14163901/2446267