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;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章