2013-04-04 55 views
0

我有2个表格:categoriesproducts用条件计数子类别

类别具有父子关系结构,并且通过加入同一个表来获取数据。

当读取数据时,我都数不过来:

  1. 多少产品每个类别包含有stock >= 1
  2. 多少子类别一个类别包含至少含有1件商品,含stock >= 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

回答

1

你可以改变你的查询中使用子查询来获得类似这样子类别的数量:

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; 

SQL Fiddle with Demo

+1

哇,这实际上是一个非常棒的解决方案:)谢谢! – vikingmaster 2013-04-04 22:15:54

0

尝试WHERE改变AND。它工作吗?

旧金山

+0

可惜似乎并不奏效。 :( – vikingmaster 2013-04-04 22:00:57