2016-06-20 27 views
1

Hallo ich eine Schwierigkeit mit einer Abfrage, wenn jemand kannSql Kategorien Produkte zählen Abfrage

Was ich versuche zu tun, wäre eine große Hilfe ist, alle Zählungen von der ausgewählten Kategorie zu erhalten. Zum Beispiel, wenn ich jede Kategorie ausgewählt habe das Ergebnis so sein wird:

Category-70 (2) <- Product-57, Product-56 
Category-64 (2) <- Product-57, Product-50 
Category-61 (1) <- Product-56 
Category-73 (1) <- Product-50 

Also das ist einfach. Ich habe eine Abfrage wie diese:

http://sqlfiddle.com/#!9/4f188/1

So würde Ich mag Kategorie-IDs zu meiner Anfrage passieren, und zählt erhalten auf der Grundlage dieser IDs, so etwas wie diese, wenn ich pass 70 Kategorie-ID das Ergebnis hat sein

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) 

wenn ich Kategorie-ID 70 und 64 das Ergebnis passieren

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] 

sein muss oder ob ich als Parameterkategorie-ID 73 geben muss das Ergebnis sein

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 

Ist das überhaupt möglich :), ty für jede Hilfe ...

Antwort

1

+1 für die SQL-Geige Beispiel sehr nützlich.

Ich glaube, das Ihr Problem beheben sollte (hinzugefügt eine Unter zu Ihrem wählen beitreten)

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 
+0

prost, die ty geholfen – Alex