进行一些练习我不知道如何进行此查询
有这2个表
StudentTable(的 IDstudent 下,....)
考试(的 IDexam ,...,学生,......,结果)
其中
例如
StudentTable
IDstudent
S0001
S0002
S0003
EXAM
IDexam student result
1 S0001 true
2 S0002 true
3 S0002 true
4 S0003 false
查询必须显示考试中真实数最多的学生的ID和数字
以示例为例 S0002 2
我试过
SELECT
student, count(1)
FROM
Exam E join StudentTable S on E.student=S.id_student
WHERE result='true'
GROUP by student
我拥有的是
S0001 1
S0002 2
但我不知道如何采取最大值
答案 0 :(得分:4)
试试这个:
SELECT
student, count(1)
FROM
Exam E join StudentTable S on E.student=S.id_student
WHERE result='true'
GROUP by student
ORDER by 2 DESC
LIMIT 0,1
MySQL中的LIMIT(N,N)子句相当于T-SQL中的 TOP(N)
答案 1 :(得分:3)
我喜欢这个查询的一件事是它支持具有最高true
个答案的重复学生。
SELECT a.*
FROM StudentTable a
INNER JOIN
(
SELECT Student
FROM Exam
WHERE result = 'true'
GROUP BY Student
HAVING COUNT(*) =
(
SELECT COUNT(*) count
FROM Exam
WHERE result = 'true'
GROUP BY Student
ORDER BY count DESC
LIMIT 1
)
) b ON a.IDStudent = b.Student
答案 2 :(得分:2)
试试这个:
SELECT
student, count(result) AS number
FROM
Exam E join StudentTable S on E.student=S.id_student
WHERE
result='true'
GROUP BY
student
HAVING
number = (SELECT COUNT(result) FROM exam WHERE result='true' GROUP BY student ORDER BY 1 DESC LIMIT 1)
链接到SQL Fiddle