我需要选择所有类别及其子类别数。
假设这是我的表格:
类别
id | title
----------
1 | colors
2 | animals
3 | plants
子类别
id | category_id | title | confirmed
------------------------------------
1 1 red 1
2 1 blue 1
3 1 pink 1
4 2 cat 1
5 2 tiger 0
6 2 lion 0
我想要的是:
id | title | count
------------------
1 colors 3
2 animals 1
3 plants 0
到目前为止我尝试过的是:
SELECT c.id, c.title, count(s.category_id) as count from categories c
LEFT JOIN sub_categories s on c.id = s.category_id
WHERE c.confirmed = 't' AND s.confirmed='t'
GROUP BY c.id, c.title
ORDER BY count DESC
此查询的唯一问题是此查询不显示具有0个子类别的类别!
任何帮助将不胜感激。
您没有获得计数为零的行的原因是该WHERE
子句检查s.confirmed
为t
,因此NULL
从外部联接结果中消除了带有s的行。
将s.confirmed
检查移到联接表达式中可解决此问题:
SELECT c.id, c.title, count(s.category_id) as count from categories c
LEFT JOIN sub_categories s on c.id = s.category_id AND s.confirmed='t'
WHERE c.confirmed = 't'
GROUP BY c.id, c.title
ORDER BY count DESC
添加Sql Fiddle:http ://sqlfiddle.com/#!17/83add/13
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句