Mysql
 SQL >> Datenbank >  >> RDS >> Mysql

EAV-Zeilen zu Spalten pivotieren, indem dieselbe Tabelle dreimal gejoint wird

Wenn eine zweite Tabelle ein Attribut pro Zeile speichert, können Sie diese Zeilen zu Spalten umwandeln, indem Sie sie einmal pro Attribut joinen und in jeder JOIN-Klausel nach var_name filtern.

SELECT t.parent_id, t.id, t.name, t.quality, t.price, c.VALUE AS color, s.VALUE AS size, r.VALUE AS rating FROM table1 t LEFT JOIN table2 c ON t.parent_id = c.parent_id AND c.var_name = 'color' LEFT JOIN table2 s ON t.parent_id = s.parent_id AND s.var_name = 'size' LEFT JOIN table2 r ON t.parent_id = r.parent_id AND r.var_name = 'rating' 

Da es LEFT JOINs sind, erscheint ein Produkt ohne Bewertungszeile trotzdem – die Bewertungsspalte kommt einfach NULL zurück. Wechseln Sie zu einem Inner Join, wenn Sie unvollständige Zeilen lieber verwerfen möchten.