我有 2 个表:categories
和 products
。
类别具有父子关系结构,通过连接同一个表来获取数据。
获取数据时,我必须计算:
- 每个类别包含多少产品,其中
库存 >= 1
- 一个类别包含多少个子类别,其中至少有 1 个产品的
库存 >= 1
SELECT c. * , count( DISTINCT s.cat_id ) AS number_of_subcategories, count( DISTINCT p.id ) AS number_of_products FROM categories c
LEFT JOIN categories s
ON s.parent_id = c.cat_id
LEFT JOIN products p
ON p.cat_id = c.cat_id AND p.stock >= 1
GROUP BY c.cat_name
ORDER BY number_of_products ASC
乍一看一切顺利,但不幸的是我得到了所有子类别的总数。
我是否又错过了一次加入,或者到目前为止我遇到了什么问题?
代码如下:SQLFiddle
最佳答案
您可以更改查询以使用子查询来获取与此类似的子类别数量:
SELECT c.cat_id,
c.parent_id,
c.cat_name,
count(sp.cat_id) AS number_of_subcategories,
count(DISTINCT p.id) AS number_of_products
FROM `categories` c
LEFT JOIN
(
select distinct s.cat_id, s.parent_id
from categories s
inner join products p
on s.cat_id = p.cat_id
where p.stock > 1
) sp
ON sp.parent_id = c.cat_id
LEFT JOIN products p
ON p.cat_id = c.cat_id
AND p.stock >= 1
GROUP BY c.cat_id, c.parent_id, c.cat_name;
关于php - 根据条件计算子类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15822331/