加入三个具有MAX功能的表

时间:2016-06-22 09:01:07

标签: mysql sql

我有三张牌桌:studentsubjectscore 我想显示每个学生max(subject_id)的详细信息。

学生表

student_id   student_name  exam_date
   1            Sharukh     24/06/12
   2            Amir        23/06/12

主题表

subject_id    sub_name
   200         Maths
   300         English
   400         Science

得分表

student_id   subject_id     score
    1           200         50 
    1           300         20
    2           300         10

结果应为:

student_id    student_name     subject_id      score
     1          Sharukh           300            20
     2          Amir              300            10

3 个答案:

答案 0 :(得分:4)

使用MAX功能和GROUP BY您的其他选择。

SELECT st.student_id, st.student_name, MAX(su.subject_id) AS subject_id, sc.score
FROM student st
INNER JOIN score sc ON st.student_id = sc.student_id
INNER JOIN subject su ON sc.subject_id = su.subject_id
WHERE su.subject_id = (SELECT MAX(sca.subject_id) 
                       FROM score sca 
                       WHERE sc.student_id = sca.student_id 
                       GROUP BY sca.student_id)
GROUP BY st.student_id, st.student_name, sc.score

输出:

student_id  student_name  subject_id  score
1           Sharukh       300         20
2           Amir          300         10

SQL小提琴:http://sqlfiddle.com/#!9/71c46a/7/0

没有GROUP BY

SELECT st.student_id, st.student_name, su.subject_id, sc.score
FROM student st
INNER JOIN score sc ON st.student_id = sc.student_id
INNER JOIN subject su ON sc.subject_id = su.subject_id
WHERE su.subject_id = (SELECT MAX(sca.subject_id) 
                       FROM score sca 
                       WHERE sc.student_id = sca.student_id 
                       GROUP BY sca.student_id)

答案 1 :(得分:3)

这里不需要使用所有三个表,你可以从表学生那里得到ans并得分。

SELECT c.student_id, c.student_name, c.subject_id, c.score FROM 
(SELECT a.student_id, a.student_name, b.subject_id, b.score FROM student 
a JOIN score b ON a.student_id = b.student_id) c JOIN 
(SELECT student_id, MAX(subject_id) AS subject_id FROM score GROUP      
BY student_id) d 
ON c.student_id = d.student_id AND c.subject_id = d.subject_id;

答案 2 :(得分:2)

试试这个;)

select t1.student_id, t1.student_name, t3.subject_id, t3.score
from student t1
inner join subject t2
inner join score t3
inner join (
    select max(subject_id) as subject_id, student_id
    from score group by student_id
) t4 on t3.student_id = t4.student_id and t3.subject_id = t4.subject_id
and t2.subject_id = t3.subject_id 
and t1.student_id = t3.student_id

SQLFiddle DEMO HERE