How make this eav query to make horizontal result

后端 未结 3 1598
离开以前
离开以前 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:13

    Let me first say this is a really poor design. Under your current approach, you will need to run multiple subqueries or joins with table aliases to achieve the result you want.

    SELECT 
        product_id,
        (
            SELECT product_attribute.value 
            FROM product_attribute, attribute 
            WHERE product_attribute.product_id=product.product_id 
            AND product_attribute.attribute_id=attribute.attribute_id
            AND product_attribute.name = 'width'
        ) AS 'width',
        (
            SELECT product_attribute.value 
            FROM product_attribute, attribute 
            WHERE product_attribute.product_id=product.product_id 
            AND product_attribute.attribute_id=attribute.attribute_id
            AND product_attribute.name = 'height'
        ) AS 'height'
    FROM
        product
    ORDER BY 
        ...      
    

    Let me suggest:

    attribute
       attribute_sid  (eg, string id)
    
    product
       product_id
       name
       ...
    
    product_attribute
       product_id   (foreign key to product table)
       attribute_sid  (foreign key to attribute table)
       value   
    

    This way, you have a definitive list of attributes, and a single attribute value per product.

    SELECT attribute_sid, value FROM product_attribute WHERE product_id = 1
    

    ... will retrieve all the attributes and values, which can conveniently be placed in a dict, array, or map.

提交回复
热议问题