gpt4 book ai didi

mysql - 使用 MAX 函数连接三个表

转载 作者:可可西里 更新时间:2023-11-01 07:17:43 27 4
gpt4 key购买 nike

我有三个表: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

最佳答案

使用 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 fiddle :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)

关于mysql - 使用 MAX 函数连接三个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37963264/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com