我正在使用MySQL 5.6。我需要获取带有产品count
列的类别列表。到目前为止,这是一个非常简单而琐碎的任务。这有点复杂:
flg_public=1
)或被禁用(flg_public=NULL
)。因此,查询应返回满足这些要求的带有产品数量的类别列表:
这是我当前的查询:
SELECT store_cat.id_cat AS id_cat,
store_cat.name AS name,
COUNT(DISTINCT store_product.id_product) AS q
FROM store_cat
LEFT JOIN store_product
ON store_product.id_cat = store_cat.id_cat
AND store_product.flg_public = 1
LEFT JOIN store_subcat
ON store_product.id_subcat = store_subcat.id_subcat
AND store_subcat.flg_public = 1
WHERE store_cat.flg_public = 1
GROUP BY store_cat.id_cat
我添加了一个sqlfiddle:http://sqlfiddle.com/#!9/43461b/1
在此示例中:
id_subcat=6
已被flg_public=0
禁用count
查询中不应考虑这1个产品。id_cat=1
,但是其中一种产品是Pantalon Flash id_product=47
,它属于被禁用的子类别Pant id_subcat=6
。 但仍在考虑中 ...Clothes类别在数量列中返回4 ...,但应为3。结果显示如下(红色更改):
有什么想法吗?谢谢!
SELECT store_cat.id_cat AS id_cat,
store_cat.name AS name,
COUNT(DISTINCT store_product.id_product) AS q
FROM store_cat
LEFT JOIN store_product
ON store_product.id_cat = store_cat.id_cat
-- AND store_product.flg_public = 1
LEFT JOIN store_subcat
ON store_product.id_subcat = store_subcat.id_subcat
-- AND store_subcat.flg_public = 1
WHERE store_cat.flg_public = 1
AND COALESCE(store_subcat.flg_public, 1)
GROUP BY store_cat.id_cat, store_cat.name ;
最少的解释置入小提琴。
您的问题是,因为您是LEFT JOIN
到store_subcat
,所以即使包含具有flg_public = 0
子类别的产品也会包含在输出行中(尝试删除GROUP BY
并更改为SELECT *
,您会看到即使Pantalon Flash
中的字段全部为store_subcat
,但NULL
仍在输出行中,因为它未通过flg_public = 1
连接条件)。要解决此问题,您需要添加一个检查,以确保store_product.id_subcat
是NULL
或store_subcat.id_subcat
不是NULL
(当产品的子类别包含flg_public = 1
时就是这种情况)。更新的查询:
SELECT store_cat.id_cat AS id_cat,
store_cat.name AS name,
COUNT(DISTINCT store_product.id_product) AS q
FROM store_cat
LEFT JOIN store_product ON store_product.id_cat = store_cat.id_cat
AND store_product.flg_public = 1
LEFT JOIN store_subcat ON store_product.id_subcat = store_subcat.id_subcat
AND store_subcat.flg_public = 1
WHERE store_cat.flg_public = 1
AND (store_product.id_subcat IS NULL OR store_subcat.id_subcat IS NOT NULL)
GROUP BY store_cat.id_cat
输出:
id_cat name q
1 Clothes 3
2 Accesories 1
3 Snacks 2
4 Other 0
6 Furniture 0
7 Bags 0
9 Pencils 1
10 Medicines 0
11 Candy 0
[请注意,Snacks
的正确计数实际上是2,而不是3。在4个零食中,Cookie wrappers
具有flg_public = 0
,因此不应包括在内,Pan de espárragos
具有id_subcat = 1
,并且子目录具有[ C0],因此也不应该包含在内。因此,在4种小吃中,应仅包含2种。