doujiao1538 2013-04-04 21:46
浏览 36
已采纳

使用条件计算子类别

I have got 2 tables: categories and products.

Categories have parent-child relationship structure and the data is fetched by joining the same table.

When fetching the data, I have to count:

  1. how many products each category contains which have stock >= 1
  2. how many subcategories a category contains which contain at least 1 product with 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

At the first glance all goes well, but unfortunately I get total number of all subcategories.

Do I miss one more join or what is my problem so far?

Here is the code: SQLFiddle

  • 写回答

2条回答 默认 最新

  • drqn5418 2013-04-04 22:11
    关注

    You could alter your query to use a subquery to get the number of subcategories similar to this:

    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;
    

    See SQL Fiddle with Demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!