我有一个电子商务商店的数据库。我想知道每个类别的有效产品数量。
代码:
SELECT c.id_category, COUNT(cp.id_product) AS nproducts
FROM ps_category AS c
LEFT JOIN ps_category_product AS cp ON cp.id_category=c.id_category
LEFT JOIN ps_product AS p ON p.id_product=cp.id_product
WHERE p.active=1
GROUP BY c.id_category
ORDER BY nproducts ASC
但是,它没有显示具有0个产品的类别。我想念什么?
答案 0 :(得分:2)
删除WHERE p.active=1
,对于没有产品的任何类别都将失败(导致查询不返回这些类别的行),并将该条件移至该ON
的{{1}}子句中。这样,您仍将为这些类别获得一个LEFT JOIN
行,这将使它们显示为具有0个产品。
NULL
请注意,要确保只计算有效产品,您需要计算SELECT c.id_category, COUNT(p.id_product) AS nproducts
FROM ps_category AS c
LEFT JOIN ps_category_product AS cp ON cp.id_category=c.id_category
LEFT JOIN ps_product AS p ON p.id_product=cp.id_product AND p.active=1
GROUP BY c.id_category
ORDER BY nproducts ASC
,而不是p.id_product
。