我有两个表-- studentlastmarks,和学生--这两个表的模式如下:
学生表有以下列: studentid,标记。
studentlastmarks表有:学生会,学生姓名,分数。
我需要在学生成绩表中得到分数大于最高分数的学生身份证明。
例如: Follwing是学生表中的数据:
studentid studentname marks
1 krishna 60
2 shiva 70
3 Arjun 50
4 Karna 65以下是学生最后标记表中的数据
studentid marks
1 65
2 65
2 50
3 70
3 60
4 40在本例中,我们需要返回学生id 2和4,因为在studentlastmarks表中,学生获得的分数大于特定学生获得的最大分数。
我尝试了下面的代码,在整个学生成绩表中给出最大分数,但我需要将它与studentlastmarks和学生表中每个学生的最大分数进行比较。
select distinct s.studentid from student as s where s.marks > (select max(sl.marks) from studentlastmarks as sl)发布于 2021-06-11 07:00:51
你可以这么做:
select s.studentid
From student s
Left join
(Select studentid, max(marks) as maxmarks
From studentlastmarks
Group by studentid) lm
On s.studentid = lm.studentid
Where s.marks > lm.maxmarks or lm.maxmarks IS NULL重要的一点是在最后一个分数表中按学生ID分组,这样您就可以在每个学生的基础上进行比较。
编辑:根据您更新的要求也显示学生没有在最后的分数,我们可以使用左连接而不是内部连接,并将过滤条件移动到一个单独的WHERE子句。对lm.maxmarks是否为null的额外检查确保在最终结果中包含没有出现在最后标记表中的学生。
发布于 2021-06-11 07:30:25
SELECT *
FROM student st
WHERE NOT EXISTS ( SELECT NULL
FROM studentlastmark sm
WHERE sm.studentid = st.studentid
AND sm.marks > st.marks );https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=52c21318eee5af1ac764dbf4d2f9dca6
两个表中的(studentid, marks)索引都将得到改进。
https://stackoverflow.com/questions/67932285
复制相似问题