我需要选择所有类别及其子类别的类别。
这里假设我的表:
类别
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个子类别的类别!
您也可以在SqlFiddle
上查看任何帮助都会非常感激。
答案 0 :(得分:4)
您没有得到零计数行的原因是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小提琴:http://sqlfiddle.com/#!17/83add/13
答案 1 :(得分:2)
我认为你也可以试试这个(它证明了你真正分组的列):
SELECT c.id, c.title, RC
from categories c
LEFT JOIN (SELECT category_id, COUNT(*) AS RC
FROM sub_categories
WHERE confirmed= 't'
GROUP BY category_id) s on c.id = s.category_id
WHERE c.confirmed = 't'
ORDER BY RC DESC