MySQL:最大计数和列名

时间:2015-09-28 12:02:49

标签: mysql

我有studentcoursestudent_has_course表。

在学生中idname ...)
当然(idname ...)
在student_has_course(student_idcourse_id

我想获得人口最多的课程"数和名称。

有了这个,我可以获得最多的课程数,但我无法弄清楚如何获得课程名称。

SELECT MAX(counted)
FROM
(
    SELECT COUNT(*) AS counted
    FROM student_has_course
    GROUP BY course_ID
) AS counts;

2 个答案:

答案 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