查询已连接表的计数不显示零计数结果

时间:2018-05-30 17:32:01

标签: mysql

我想从父行返回行,其中子行数与父ID相关。不幸的是,我遇到了一个问题,我的查询只返回带子行的行,没有子行的行不会返回结果。我尝试过LEFT,RIGHT,OUTER和INNER联接无济于事。 SQLFiddle链接和查询如下:

SELECT t.id, t.name, COUNT(s.id) AS cnt FROM top AS t 
JOIN sub AS s ON t.id = s.top_id GROUP BY t.id, t.name 
ORDER BY t.id ASC

http://sqlfiddle.com/#!9/c466fe/1

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

似乎你需要LEFT JOIN

http://sqlfiddle.com/#!9/c466fe/4

SELECT t.id, 
       t.name, 
       COUNT(s.id) AS cnt 
FROM top AS t 
LEFT JOIN sub AS s 
ON t.id = s.top_id 
GROUP BY t.id, t.name 
ORDER BY t.id ASC

答案 1 :(得分:1)

SELECT t.id, t.name, COUNT(s.id) AS cnt 
FROM top AS t 
left JOIN sub AS s ON t.id = s.top_id GROUP BY t.id, t.name 
ORDER BY t.id ASC