我有2张桌子:产品&类
我正在尝试编写sql来计算每个类别的产品数量。到目前为止,我有这个:
SELECT `name`, count(*) as `size`
FROM products
INNER JOIN category ON category.`id` = products.`categoryID`
GROUP BY category.`name`
这将返回每个类别名称的列表以及该类别的产品数量。但是,它不会列出包含0个产品的类别。我该如何解决这个问题?
答案 0 :(得分:2)
使用正确的联接。
SELECT `name`, count(*) as `size`
FROM products
RIGHT JOIN category ON category.`id` = products.`categoryID`
GROUP BY category.`name`
答案 1 :(得分:0)
尝试:
SELECT `name`, count(products.id) as `size`
FROM category
LEFT JOIN products ON category.`id` = products.`categoryID`
GROUP BY category.`name`