SELECT 内部聚合函数

SELECT inside Aggregate Function

假设我有 3 个这样的表:

class
id
capacity

student
id

student_class
id_student
id_class
SELECT c.id
FROM student_class sc
JOIN class c
  ON c.id=sc.id_class
JOIN student s
  ON s.id=sc.id_student
HAVING MAX((SELECT(COUNT(sc2.id) FROM student_class sc2 WHERE sc2.id_student=s.id AND sc2.id_course=c.id)/c.capacity))

我想找到 enrolled/capacity 比率最高的课程。

我应该在聚合函数中使用 select 子句来编写这样的 having 子句吗?

HAVING MAX((query that gives me the total number of students enrolled in a course)/course capacity))

或者有更好的方法吗?

I want to find the course with the highest enrolled/capacity ratio.

您将使用聚合来计算比率。然后你可以用ORDER BYLIMIT来return一个值。请注意,这 return 是一行,即使有并列:

SELECT c.id, COUNT(*) / c.capacity as ratio
FROM student_class sc JOIN
     class c
     ON c.id = sc.id_class
GROUP BY c.id, c.capacity
ORDER BY ratio DESC
LIMIT 1;