考虑连接两个表,在重复行上获取最大值

时间:2013-03-11 15:47:31

标签: mysql sql greatest-n-per-group

我有两张桌子

students_tbl

students_results_tbl

students_tbl

------------------------------------------------------
student_id | student_name | 
------------------------------------------------------
1            Mark
2            Jhon
3            Michael
4            Steven  
------------------------------------------------------

students_results_tbl

------------------------------------------------------
student_id | course_id | student_mark 
------------------------------------------------------
1            33            100
2            2             50
3            33            200  
4            10            80 
------------------------------------------------------

我的问题,我想根据具有最高分的特定课程ID从结果表中选择所有内容,如果只重复了course_id,则根据结果表中生成的学生ID从学生表中选择学生名称

3 个答案:

答案 0 :(得分:1)

据我了解您的问题,您希望获得每门课程的最高学生

SELECT  a.*, b.*
FROM    students_tbl a
        INNER JOIN students_results_tbl b
            ON a.student_id = b.student_id
        INNER JOIN
        (
            SELECT  course_ID, MAX(student_mark) max_grade
            FROM    students_results_tbl
            GROUP   BY course_ID
        ) c ON  b.course_id = c.course_id  AND
                b.student_mark = c.max_grade

RESULT

╔════════════╦══════════════╦═══════════╦══════════════╗
║ STUDENT_ID ║ STUDENT_NAME ║ COURSE_ID ║ STUDENT_MARK ║
╠════════════╬══════════════╬═══════════╬══════════════╣
║          2 ║ Jhon         ║         2 ║           50 ║
║          3 ║ Michael      ║        33 ║          200 ║
║          4 ║ Steven       ║        10 ║           80 ║
╚════════════╩══════════════╩═══════════╩══════════════╝

更新1

要获得更快的效果,请在INDEX上添加化合物course_id and student_mark

ALTER TABLE students_results_tbl INDEX (course_id, student_mark)

更新2

SELECT  a.*, b.*
FROM    students_tbl a
        INNER JOIN students_results_tbl b
            ON a.student_id = b.student_id
        INNER JOIN
        (
            SELECT  student_id,
                    course_ID, 
                    MAX(student_mark) max_grade
            FROM    students_results_tbl 
            GROUP   BY student_id, course_ID
        ) c ON  b.course_id = c.course_id  AND
                b.student_ID = c.student_id AND
                b.student_mark = c.max_grade
WHERE   b.course_ID = 33

答案 1 :(得分:0)

也许是这样,如果我正确理解你的问题

SELECT MAX(student_mark)
FROM students_results_tbl
WHERE course_id = ???
GROUP BY course_id
HAVING COUNT(course_id) > 1

答案 2 :(得分:0)

此查询将返回所有course_id,其中包含结果表中有多个记录的最大学生标记

SELECT course_id, MAX(student_mark)
FROM students_resultstbl r
GROUP BY course_id HAVING COUNT (r.student_id) > 1