mysql 应用查询 三个表(学生表,课程表,学生课程分数表) student, course, score表
当咸鱼拥有了梦想,它就会成为,一只拥有梦想的咸鱼。
有三个表
表一:course 表
表二:student
标三:course_score 表
问题1:查询各科平均成绩,格式要求 cid, cname, 平均成绩(score)
SELECT c.cid, cname, score FROM course c LEFT JOIN ( SELECT cid, AVG( score ) AS score FROM `course_score` GROUP BY cid ) tem ON tem.cid = c.cid;
执行结果:
注意:使用到了聚合函数 AVG, 然后进行一个连表查询
问题2:查询总分数前3的学生数据,格式要求:sid, sname, total_score
方法一:使用普通的查询
SELECT s.sid, sname, total_score FROM student s, ( SELECT sid, sum( score ) AS total_score FROM course_score GROUP BY sid ORDER BY total_score DESC LIMIT 3 ) tem WHERE tem.sid = s.sid;
方法二:使用INNER JOIN
SELECT s.sid, sname, total_score FROM student s INNER JOIN ( SELECT sid, sum( score ) AS total_score FROM course_score GROUP BY sid ORDER BY total_score DESC LIMIT 3 ) tem ON tem.sid = s.sid;
执行结果:
问题3:查询各科成绩都高于各科平均分的同学信息,格式要求: sid, sname
SELECT sid, sname FROM student WHERE sid IN ( SELECT a.sid FROM ( SELECT sid FROM course_score cs INNER JOIN ( SELECT cid, AVG( score ) avg_score FROM `course_score` GROUP BY cid ) tem ON tem.cid = cs.cid WHERE cs.score > tem.avg_score ) a GROUP BY sid HAVING count( sid ) = ( SELECT count( * ) FROM course ) )
思路:先分组查询成绩大于平均成绩的数据数据 同时 添加having 条件 总的科目和 大于平均成绩的count 相等
执行结果:
问题4:统计并列出各科各个分数段人数,格式要求:课程id, 课程名称,100-90, 89-70, 69-60, <60等分数段的人数
SELECT c.cid, cname, count( CASE WHEN score > 89 THEN 1 END ) AS '100-90', count( CASE WHEN score < 90 AND score > 69 THEN 1 END ) AS '89-70', count( CASE WHEN score < 70 AND score > 59 THEN 1 END ) AS '69-60', count( CASE WHEN score < 60 THEN 1 END ) AS '<60' FROM `course_score` cs INNER JOIN course c ON c.cid = cs.cid GROUP BY cid
执行结果:
问题5: 查询各科成绩前三名的数据(按学科排序,不考虑学科并列) 要求格式:cid, cname, sid, sname
SELECT c.cid, cname, cs.sid, s.sname FROM course c JOIN course_score cs ON cs.cid = c.cid JOIN student s ON s.sid = cs.sid WHERE ( SELECT count( * ) FROM course_score cc WHERE cc.score > cs.score AND cc.cid = cs.cid ) < 3 ORDER BY cs.cid, cs.score
执行结果:
注解:
当 < 3 的条件改为
< 1 (也就是 = 0) 时,即子表中相同班级没有比主表分数高的学生,则取得分数最高的学生;
< 2 (也就是 = 1) 时,即子表中相同班级里只有一个比主表分数高的学生,则取得分数排名前二的学生;
< 3 (也就是 = 2) 时,即子表中相同班级里只有二个比主表分数高的学生,则取得分数排名前三的学生;
是不是很有意思
最新评论