2012-04-04 9 views
0

Ich versuche, eine Liste (aus vier Tabellen) von Produkten, Classid, Optionid, 'Bilder' zu generieren. Jedes Produkt kann viele ClassIDs (eins zu viele) haben, jede ClassID kann viele OptionID haben, und jede OptionID kann viele viele Bilder haben. Abschließend möchte ich für die Bilder Tabelle (xcart_images_D) zählen, wie viele Bilder jede ProduktID hat. Wie kann ich alle diese Informationen effektiv abfragen, ohne mehrere Anweisungen zu verwenden?Drei Tabelle Join Problem mit Count

Hier ist die grundlegenden Informationen für jede der Tabellen

xcart_products 
    + productid* 
    + product 
xcart_classes - 
    + classid* 
    + productid (xcart_products.productid) 
xcart_class_options - 
    + optionid* 
    + classid (xcart_classes.classid) 
    + option_name 
xcart_images_D - 
    + imageid* 
    + optionid (xcart_class_options.optionid) 
+ id (xcart_products.productid) 

* primary/foreign key 

Ich habe die drei Join-Tabelle arbeiten, aber ich kann nicht die xcart_images_D Tabelle noch an der Arbeit verstehe ich, wie ich die Zählung erreichen würde. Kann mir jemand in die richtige Richtung zeigen?

Für das wert, was es ist, hier ist meine drei Tisch

SELECT xp.productid, xp.product, xc.classid, xco.optionid, xco.option_name 
FROM xcart_products xp 
JOIN xcart_classes xc ON xp.productid = xc.productid and xc.class = 'Color' 
JOIN xcart_class_options xco ON xc.classid = xco.classid 
WHERE xc.class = 'Color' 
ORDER by xp.productid DESC 

beitreten Wenn ich versuche, und fügen Sie die folgenden Zeilen die Anzahl der Ergebnisse um etwa die Hälfte reduziert werden.

JOIN xcart_images_D xi ON xi.optionid = xco.optionid 
GROUP BY xp.productid 

Antwort

1
SELECT xp.productid, count(xi.imageid) 
FROM xcart_products xp 
INNER JOIN xcart_classes xc ON xp.productid = xc.productid AND xc.class = 'Color' 
INNER JOIN xcart_class_options xco ON xc.classid = xco.classid 
INNER JOIN xcart_images_D xi ON xi.optionid = xco.optionid 
GROUP BY xp.productid 
ORDER by xp.productid DESC 
+0

Vielen Dank für die Hilfe. Aus irgendeinem Grund, wenn ich die Zählung hinzufügen, schrumpft die Anzahl der gezogenen Ergebnisse von 2.000 auf etwa 200. Irgendeine Idee, warum? – Eric