如果有人可以提供帮助,那么我对一个查询有困难
我要做的是按所选类别获取所有计数。例如,如果我没有选择任何类别,结果将是这样的:
Category-70 ( 2 ) <- Product-57, Product-56
Category-64 ( 2 ) <- Product-57, Product-50
Category-61 ( 1 ) <- Product-56
Category-73 ( 1 ) <- Product-50
这很容易。我有一个像这样的查询:
http://sqlfiddle.com/#!9/4f188/1
所以我想将类别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]
或者如果我作为参数类别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为任何帮助......
答案 0 :(得分:1)
+1为SQL小提琴示例,非常有用。
我认为这可以解决您的问题(为您的加入添加子选择)
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