【问题标题】:SQL Query to get All the students id whose mark is greater than previous examSQL查询获取所有分数大于上一次考试的学生id
【发布时间】:2021-06-11 06:36:44
【问题描述】:

我有两个表studentstudentlastmarks,两者的架构如下:

student 表有以下列:studentid、marks。

studentlastmarks 表有:studentid、studentname、marks。

我需要在 studentlastmarks 表中获取分数大于他们最大分数的学生 ID。

例如: 以下是学生表中的数据:

studentid           studentname            marks
1                    krishna                60
2                    shiva                  70
3                    Arjun                  50
4                    Karna                  65

以下是studentlastmark表中的数据

studentid            marks
1                      65
2                      65
2                      50
3                      70
3                      60
4                      40

在本例中,我们需要返回学生 id 2 和 4 ,因为 student 在 student 表中获得的分数大于特定学生在 studentlastmarks 中获得的最大分数> 表。

我已经尝试了以下代码,它在整个 studentlast 标记表中给出了最高分,但我需要将它与 studentlastmarksstudent 表中每个学生的最高分进行比较

select distinct s.studentid from student as s where s.marks > (select max(sl.marks) from studentlastmarks as sl)

【问题讨论】:

  • 到目前为止你尝试过什么?你被困在哪里了?
  • 查找最大值。在子查询中标记 studentlastmarks,然后加入并比较。
  • @shree.pat18 我试着用这个 select distinct s.studentid from student as s where s.marks > (select max(sl.marks) from studentlastmarks as sl) 它给了我有分数的学生大于整个 studentlastmark 的最大值。但我需要每个学生的最高分。
  • 是否必须退回studentlastmarks中未出现的学生?
  • 请注意,在现实世界中,不太可能以这种方式构造数据

标签: mysql sql


【解决方案1】:

你可以这样做:

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 分组,以便您可以根据每个学生进行比较。

编辑:根据您更新后的要求,也显示学生不在最后分数,我们可以使用 LEFT JOIN 而不是 INNER JOIN,并将过滤条件移动到单独的 WHERE 子句。 lm.maxmarks 是否为空的额外检查可确保未出现在最后成绩表中的学生包含在最终结果中

【讨论】:

    【解决方案2】:
    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) 在两个表中的索引都会得到改善。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-09
      • 2017-03-30
      • 1970-01-01
      • 2021-08-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多