Mysql
 sql >> Datenbank >  >> RDS >> Mysql

Wie machen Sie diese eav-Abfrage, um ein horizontales Ergebnis zu erzielen?

Es gibt mehrere Möglichkeiten, dies zu implementieren. So etwas sollte funktionieren, indem es für jeden Attributwert mehrmals auf die Tabelle zurückverknüpft wird:

SELECT p.product_id,
    a.value height,
    a2.value width
FROM Product p
    JOIN Product_Attribute pa ON p.product_id = pa.product_id 
    JOIN Attribute a ON pa.attribute_id = a.attribute_id AND a.name = 'height'
    JOIN Product_Attribute pa2 ON p.product_id = pa2.product_id 
    JOIN Attribute a2 ON pa2.attribute_id = a2.attribute_id AND a2.name = 'width'

Und hier ist der Fiddle .

Hier ist ein alternativer Ansatz mit MAX und GROUP BY, den ich persönlich bevorzuge:

SELECT p.product_id,
    MAX(Case WHEN a.name = 'height' THEN a.value END) height,
    MAX(Case WHEN a.name = 'width' THEN a.value END) width
FROM Product p
    JOIN Product_Attribute pa ON p.product_id = pa.product_id 
    JOIN Attribute a ON pa.attribute_id = a.attribute_id 
GROUP BY p.product_id

Viel Glück.