我有这个查询
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)
这里是截图
表教室
表 class_history
注意:如果容量已满,则表明它没有出现,如果未满,则无论是否为0都会出现
答案 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