类别表
+----+------+
| id | name |
+----+------+
| 1 | cat1 |
| 2 | cat2 |
| 3 | cat3 |
+----+------+
产品表
+----+-------+--------+
| id | name | cat_id |
+----+-------+--------+
| 1 | prod1 | 1 |
| 2 | prod2 | 1 |
| 3 | prod3 | 3 |
| 4 | prod4 | 1 |
| 5 | prod5 | 3 |
| 6 | prod6 | 1 |
+----+-------+--------+
这是我的疑问:
SELECT c.id, c.name, count( p.cat_id ) num
FROM categories c
INNER JOIN products p ON c.id = p.cat_id
GROUP BY p.cat_id
结果是:
+----+------+-------+
| id | name | count |
+----+------+-------+
| 1 | cat1 | 4 |
| 3 | cat3 | 2 |
+----+------+-------+
现在出现错误显示计数cat = 2 如何修复得到这个结果:
+----+------+-------+
| id | name | count |
+----+------+-------+
| 1 | cat1 | 4 |
| 2 | cat2 | 0 |
| 3 | cat3 | 2 |
+----+------+-------+
答案 0 :(得分:4)
我认为,您只需将联接更改为左联接。
SELECT c.id, c.name, count( p.cat_id ) num
FROM categories c
LEFT JOIN products p ON c.id = p.cat_id
GROUP BY p.cat_id
答案 1 :(得分:1)
您需要使用left join
SELECT c.id, c.name, count( p.cat_id ) num
FROM categories c
LEFT JOIN products p ON c.id = p.cat_id
GROUP BY p.cat_id
参考:What's the difference between INNER JOIN, LEFT JOIN, RIGHT JOIN and FULL JOIN?
答案 2 :(得分:0)
SELECT c.id, c.name, count( p.cat_id ) num
FROM categories c
LEFT JOIN products p ON c.id = p.cat_id
GROUP BY p.cat_id
答案 3 :(得分:0)
每个答案都是正确的,您需要使用LEFT JOIN
来达到指定的结果。要获得您请求的完全结果,您需要执行以下操作:
SELECT c.id, c.name, COUNT(p.cat_id) AS `count`
FROM categories AS c
LEFT JOIN products AS p ON c.id = p.cat_id
GROUP BY p.cat_id
ORDER BY c.id ASC
SO question Boby referenced很好地解释了为什么你不能使用INNER JOIN
来达到理想的结果。