只有成绩最好的学生

时间:2018-09-24 18:38:35

标签: mysql sql

我在学生和成绩之间有一个简单的关系:

学生:

+------------+-------------+
| idStudent  | NameStudent |
+------------+-------------+
|         1  | Student A   |
|         2  | Student B   |
|         3  | Student C   |
+------------+-------------+

标记:

+----------+------+-----------+
| idMarks  | mark | idStudent |
+----------+------+-----------+
|        1 | A    |         1 |
|        2 | A    |         1 |
|        3 | A    |         1 |
|        4 | A    |         2 |
|        5 | A    |         2 |
|        6 | C    |         3 |
|        7 | A    |         3 |
+----------+------+-----------+

我只想让每门通过考试的学生都获得“ A”的成绩

SELECT *, COUNT(mark)
FROM student S
INNER JOIN marks M ON S.idStudent = M.idStudent
WHERE M.mark = "A"
GROUP BY S.idStudent

我尝试了这个,但是当我尝试比较他们通过的考试数量和他们获得的A数量时,我陷入僵局...

我也尝试了子查询,但是没有用

3 个答案:

答案 0 :(得分:2)

  • 按学生分组
  • 找到学生获得的所有明显标记,并使用Group_concat函数将它们放在逗号分隔的字符串中
  • 只需过滤(使用Having子句)只有一个整体明显标记的标记,即 A

使用以下查询:

SELECT S.idStudent, 
       S.NameStudent, 
       GROUP_CONCAT(DISTINCT M.mark) AS unique_marks 
FROM student S
INNER JOIN marks M ON S.idStudent = M.idStudent
GROUP BY S.idStudent, S.NameStudent
HAVING unique_marks = 'A'

答案 1 :(得分:2)

您可以使用HAVING

SELECT S.idStudent
FROM student S
INNER JOIN marks M ON S.idStudent = M.idStudent
GROUP BY S.idStudent
HAVING COUNT(mark)=SUM(mark='A');-- compare all marks with marks that are only 'A'
                                 -- if equal then every mark is 'A'

答案 2 :(得分:2)

如果您只需要学生证,则可以LEFT JOIN个学生进行标记,包括join子句中标记不为A的条件。然后,WHERE子句将仅包括具有不匹配的行:

SELECT Student.idStudent 
FROM Student
    LEFT JOIN Marks BelowA ON
        BelowA.idStudent = Student.idStudent
        AND BelowA.mark <> 'A'
WHERE BelowA.idStudent IS NULL