[英]How to count rows in one table based on another table in mysql 2
I checked this answer but I have a problem. 我检查了这个答案,但是有问题。
SQL Fiddle (I changed INNER JOIN
to LEFT JOIN
) SQL提琴 (我将
INNER JOIN
更改为LEFT JOIN
)
What if there is a row in my departments
(DDD for example) and no association in the courses
table . 如果我的
departments
有一行(例如DDD)并且courses
表中没有关联怎么办?
As you can see in the fiddle the count for DDD department is 1 like the BUS department has even if there is no data for DDD department. 正如您在小提琴中看到的那样,即使没有DDD部门的数据,DDD部门的计数也像BUS部门一样为1。 I know that
LEFT JOIN
does this but how can I modify this ? 我知道
LEFT JOIN
,但是我该如何修改呢?
How do I get count = 0 for the DDD department? 我如何获得DDD部门的count = 0?
Try COUNT(c.section)
so when section results null for no association then in count it evaluates to zero 尝试使用
COUNT(c.section)
这样当section没有关联时结果为null时,计数为零
SELECT d.abbreviation
, COUNT(c.section) num
FROM departments d
LEFT JOIN courses c ON c.section LIKE CONCAT(d.abbreviation, "%")
GROUP BY d.abbreviation
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.