Mysql Sql类别产品计数查询

Mysql Sql类别产品计数查询,mysql,sql,count,product,categories,Mysql,Sql,Count,Product,Categories,嗨,我有一个问题,如果有人可以帮助将是巨大的困难 我要做的是按所选类别获取所有计数。例如,如果我没有选择任何类别,结果如下: Category-70 ( 2 ) <- Product-57, Product-56 Category-64 ( 2 ) <- Product-57, Product-50 Category-61 ( 1 ) <- Product-56 Category-73 ( 1 ) <- Product-50 所以这很容易。我有一个类似这样的问题: 因此

嗨,我有一个问题,如果有人可以帮助将是巨大的困难

我要做的是按所选类别获取所有计数。例如,如果我没有选择任何类别,结果如下:

Category-70 ( 2 ) <- Product-57, Product-56
Category-64 ( 2 ) <- Product-57, Product-50
Category-61 ( 1 ) <- Product-56
Category-73 ( 1 ) <- Product-50
所以这很容易。我有一个类似这样的问题:

因此,我想将类别id传递给我的查询,并基于该id获取计数,类似于这样,如果我传递类别id 70,结果必须是

Category-70 ( 2 ) <- Product-57, Product-56
Category-64 ( 1 ) <- Product-57, [Product-50 is gone because is not in cateogry id 70]
Category-61 ( 0 )
Category-73 ( 0 )
如果我通过类别id 70和64,结果必须是

Category-70 ( 1 ) <- Product-57, [Product-56 is gone because is not in category 70 and 64]
Category-64 ( 1 ) <- Product-57
Category-61 ( 0 ) [Product-56 is gone, because is not in category 70 and 64 ]
Category-73 ( 0 ) [Product-50 is gone because is not in category 70 and 64]
或者,如果我给出参数category id 73,那么结果必须是

Category-70 ( 0 ) [products are not counted because they are not in 73]
Category-64 ( 1 ) <- Product-50
Category-61 ( 0 ) [products are not counted because they are not in 73]
Category-73 ( 1 ) <- Product-50

这可能吗:,ty需要任何帮助…

+1对于SQL fiddle示例,非常有用

我相信这会解决你的问题,添加一个子选择到你的加入

SELECT Concat('Category-',c.category_id), 
count(DISTINCT p2c.product_id) as products 
FROM category c 
LEFT JOIN product_to_category p2c 
  ON (c.category_id = p2c.category_id AND p2c.product_id) AND p2c.product_id in
  (select product_id from product_to_category where category_id = @input)
LEFT JOIN category_path cp ON (cp.category_id = c.category_id AND cp.path_id = c.category_id)    
WHERE
cp.level <= 2 
GROUP BY c.category_id
ORDER BY c.sort_order