mysql练习,查询某班级中各科成绩最高的学生信息

班级表class

 

成绩表source

 

 

学生表student


 

 1、查询班级一班的各科成绩最高的学生信息

使用左连接 left join
SELECT
a.stuid, a.stuname, a.course, a.source, a.classname FROM ( SELECT student.stuid, student.stuname, source.course, source.source, class.classname FROM student LEFT JOIN class ON class.classid = student.classid LEFT JOIN source ON student.stuid = source.stuid WHERE class.classname = '一班' ) AS a LEFT JOIN ( SELECT student.stuid, student.stuname, source.course, source.source, class.classname FROM student LEFT JOIN class ON class.classid = student.classid LEFT JOIN source ON student.stuid = source.stuid WHERE class.classname = '一班' ) AS b ON a.source < b.source AND a.course = b.course WHERE b.course IS NULL

 

SELECT a.stuid, a.stuname, a.classname, a.course, a.source FROM(
SELECT student.stuid, student.stuname, class.classname, source.course, source.source FROM student
JOIN class ON class.classid = student.classid AND class.classname = '一班'
JOIN source ON source.stuid = student.stuid) AS a
JOIN (
    SELECT b.stuid, b.stuname, b.classname, b.course, max(b.source) as max_source FROM(
    SELECT student.stuid, student.stuname, class.classname, source.course, source.source FROM student
    JOIN class ON class.classid = student.classid AND class.classname = '一班'
    JOIN source ON source.stuid = student.stuid) AS b
    GROUP BY b.course
) AS c
ON c.course = a.course AND c.max_source = a.source

 

posted @ 2020-07-19 00:26  静心_心静  阅读(8645)  评论(0编辑  收藏  举报