我有2個表 - 分類和產品。我想獲得每個類別下的產品總數?我的表看起來像:如何使用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 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`
應該不是你的JOIN子句是'ON c.category_id = p.category_id'? –
哦,是的大錯誤! – user5307298