如何使用mysql连接查找每个类别下的产品总数?

时间:2015-12-21 14:36:22

标签: mysql

我有2张桌子 - 粪便和产品。我想获得每个类别下的产品总数?我的表格如下:

类别

category_id     category_name
1               first category
2               second category
3               third category

产品

product_id     product_name     category_id
1              first product    1
2              second product   1
3              third product    1
4              fourth product   3
5              fifth product    3

我想要关注输出:

category_id     category_name     total_products
1               first category    3
2               second category   0
3               third category    2

我目前正在使用以下sql,但它没有让我得到正确的结果:

SELECT `c`.`category_id`, `c`.`category_name`, COUNT(`p`.`product_id`) AS total_products FROM `categories` AS `c` INNER JOIN `products` AS `p` ON `c`.`category_id` = `p`.`product_id` GROUP BY `p`.`category_id`

1 个答案:

答案 0 :(得分:1)

您需要使用左连接作为

select
c.*, coalesce(count(p.category_id),0) as total_products
from categories c
left join products p on p.category_id = c.category_id
group by c.category_id ;