一、案例(接上一篇文章)
09)查询学过「张三」老师授课的同学的信息
-- 一共有两种方式
-- 第一种方式:
SELECT s.*,c.cname,t.tname,sc.score
FROMt_mysql_teacher t,t_mysql_course c,t_mysql_student s,t_mysql_score sc
WHEREt.tid = c.tidand c.cid = sc.cidand sc.sid = s.sidand t.tname = '张三'
-- 第二种方式:
-- select * from t_mysql_student where sid in(
-- select sid from t_mysql_score where cid=(select cid from t_mysql_course where tid=
-- (select tid from t_mysql_teacher where tname='张三')))
10)查询没有学全所有课程的同学的信息
SELECTs.sid,s.sname,count(sc.score) n
FROMt_mysql_student s LEFT JOIN t_mysql_score sc ON s.sid = sc.sid
GROUP BY s.sid,s.sname
HAVING n < (SELECT count(*) from t_mysql_course)
11)查询没学过"张三"老师讲授的任一门课程的学生姓名
SELECTs.sid,s.sname
FROMt_mysql_score sc,t_mysql_student s
WHEREs.sid = sc.sid AND sc.cid NOT IN ( SELECT cid FROM t_mysql_course c, t_mysql_teacher t WHERE c.tid = t.tid AND t.tname = '张三' )
GROUP BYs.sid,s.sname
12)查询两门及其以上不及格课程的同学的学号,姓名及其平均成绩
SELECTs.sid,s.sname,ROUND(avg( sc.score ),2) 平均成绩
FROMt_mysql_student s,t_mysql_score sc
WHEREs.sid = sc.sid and sc.score < 60
GROUP BYs.sid,s.sname
13)检索" 01 "课程分数小于 60,按分数降序排列的学生信息
SELECTs.*,sc.cid,sc.score 分数
FROMt_mysql_score sc,t_mysql_student s
WHEREs.sid = sc.sid AND sc.cid = '01' AND score < 60
ORDER BYsc.score DESC
14)按平均成绩从高到低显示所有学生的所有课程的成绩以及平均成绩
SELECTs.sid,s.sname,sum((CASE WHEN sc.cid='01' THEN sc.score END)) 语文,sum((CASE WHEN sc.cid='02' THEN sc.score END)) 数学,sum((CASE WHEN sc.cid='03' THEN sc.score END)) 英语,ROUND(avg(sc.score),2) 平均成绩
FROMt_mysql_score sc RIGHT JOIN t_mysql_student s ON sc.sid = s.sid
GROUP BYs.sid,s.sname
15)查询各科成绩最高分、最低分和平均分:
以如下形式显示:课程 ID,课程 name,最高分,最低分,平均分,及格率,中等率,优良率,优秀率及格为>=60,中等为:70-80,优良为:80-90,优秀为:>=90要求输出课程号和选修人数,查询结果按人数降序排列,若人数相同,按课程号升序排列
SELECTc.cid,c.cname,count(sc.sid) 人数,max(sc.score) 最高分,min(sc.score) 最低分,ROUND(avg(sc.score),2) 平均分,CONCAT(ROUND(sum(if(sc.score>=60,1,0))/(SELECT count(1) from t_mysql_student)*100,2),'%') 及格率,CONCAT(ROUND(sum(if(sc.score>=70 and sc.score<80,1,0))/(SELECT count(1) from t_mysql_student)*100,2),'%') 中等率,CONCAT(ROUND(sum(if(sc.score>=80 and sc.score<90,1,0))/(SELECT count(1) from t_mysql_student)*100,2),'%') 优良率,CONCAT(ROUND(sum(if(sc.score>=90,1,0))/(SELECT count(1) from t_mysql_student)*100,2),'%') 优秀率
FROMt_mysql_score sc LEFT JOIN t_mysql_course cON sc.cid = c.cid
GROUP BY c.cid,c.cname
二、思维导图