我有student
,course
和student_has_course
表。
在学生中id
,name
...)
当然(id
,name
...)
在student_has_course(student_id
,course_id
)
我想获得人口最多的课程"数和名称。
有了这个,我可以获得最多的课程数,但我无法弄清楚如何获得课程名称。
SELECT MAX(counted)
FROM
(
SELECT COUNT(*) AS counted
FROM student_has_course
GROUP BY course_ID
) AS counts;
答案 0 :(得分:1)
尝试此查询
SELECT COUNT(shc.course_id) as cnt, c.name
FROM student_has_course shc
JOIN course c ON (c.course_id = shc.course_id)
GROUP BY shc.course_id
ORDER BY cnt DESC
LIMIT 1
答案 1 :(得分:1)
SELECT c.name, sc.cnt
FROM
course c
INNER JOIN (SELECT course_id, COUNT(*) as cnt FROM student_has_course GROUP BY 1 ORDER BY 2 DESC LIMIT 1) cs ON c.id=cs.course_id