How make this eav query to make horizontal result

后端 未结 3 1608
离开以前
离开以前 2021-01-03 05:33

The case:

tables:

product:
product_id|name        |
------------------------
1         |iphone 4    |
2         |gallaxy 2   |
3         |blackbery 6         


        
3条回答
  •  青春惊慌失措
    2021-01-03 06:12

    There are several ways to implement this. Something like this should work joining back on the table multiple times for each attribute value:

    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'
    

    And here is the Fiddle.

    Here is an alternative approach using MAX and GROUP BY that I personally prefer:

    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
    

    Good luck.

提交回复
热议问题