我有一个包含“教师” PIN的表“老师”,以及一个包含“教师”引用老师的“表”学生。这个想法是一位老师包含一定数量的学生。
我的任务是找到学生最多的老师。我目前正在使用查询:
select t.TeacherPIN, count(s.TeacherPIN)
from Teacher t, Student s
where t.TeacherPIN = s.TeacherPIN
and ((select count(s1.TeacherPIN) from Student s1 where s1.TeacherPIN = t.TeacherPIN) >=
(select count(s2.TeacherPIN) from Student s2 where s2.TeacherPIN = (select t1.TeacherPIN from Teacher t1)));
我确定我正在使这种方式变得比我应该的复杂,但是我已经从事了一段时间,希望有人可以将我推向正确的方向。
谢谢!
最佳答案
要查找最多人数的一位老师(可能是很多):
SELECT TeacherPIN
, COUNT(*) AS NumberOfStudents
FROM Student
GROUP BY TeacherPIN
ORDER BY NumberOfStudents DESC
LIMIT 1
要找到所有这些:
SELECT TeacherPIN
, COUNT(*) AS NumberOfStudents
FROM Student
GROUP BY TeacherPIN
HAVING COUNT(*) =
( SELECT COUNT(*) AS NumberOfStudents
FROM Student
GROUP BY TeacherPIN
ORDER BY NumberOfStudents DESC
LIMIT 1
)