获取具有相同ID列的特定COUNT值

时间:2014-10-01 05:57:58

标签: mysql sql request

我有这个查询

SELECT * 
FROM classroom 
WHERE capacity > (SELECT COUNT(class_history.*) 
                  FROM classroom 
                  RIGHT JOIN class_history ON classroom.id_class = class_history.id_class 
                  GROUP BY class_history.id_class) 
ORDER BY id_class DESC

我希望通过计算class_history记录获得课堂容量,与课堂ID相同,任何人都可以帮我解决此问题吗?

所以我可以得到这样的回报

classroom 1 - capacity  (0/20)
classroom 2 - capacity  (2/20)
classroom 3 - capacity  (9/10)

这里是截图

教室 classroom

class_history class_history

注意:如果容量已满,则表明它没有出现,如果未满,则无论是否为0都会出现

1 个答案:

答案 0 :(得分:1)

使用LEFT JOIN,它应该解决您的问题

SELECT classroom.id_class, COUNT(class_history.id_class), capacity 
FROM classroom LEFT JOIN class_history
ON classroom.id_class = class_history.id_class
GROUP BY classroom.id_class
HAVING COUNT(class_history.id_class) < capacity