如何使用mysql连接查找每个类别下的产品总数?
我有两张桌子——类别和产品。我想得到每个类别下的产品总数?我的桌子看起来像: 表类别如何使用mysql连接查找每个类别下的产品总数?,mysql,Mysql,我有两张桌子——类别和产品。我想得到每个类别下的产品总数?我的桌子看起来像: 表类别 category_id category_name 1 first category 2 second category 3 third category product_id product_name category_id 1 first product 1 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
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`
您需要使用left join作为
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 ;
你的JOIN子句不应该是c.category\u id=p.category\u id上的
吗?这里实际上不需要合并,但我知道你的问题出在哪里了。我的问题已经解决了,将代码改为@Patrick fournie的上述注释,你确定内部JOIN
也列出了0个计数吗?