Yos*_*sef 4 mysql sql entity-attribute-value
案子:
表:
product:
product_id|name |
------------------------
1 |iphone 4 |
2 |gallaxy 2 |
3 |blackbery 6 |
product_attribute:
id|product_id|attribute_id
--------------------------------------------------
1 |1 |2
2 |1 |6
. . .
attribute:
------------------------------
attribute_id|name |value|
1 |width |300
2 |width |320
3 |width |310
4 |height|390
5 |height|370
6 |height|380
Run Code Online (Sandbox Code Playgroud)
应该得到结果:
product_id|height|width
1 |380 |320
......................
Run Code Online (Sandbox Code Playgroud)
编辑: 高度和宽度属性只是产品属性的一部分 - 产品需要具有动态能力,由用户在后端添加,就像在magento中一样,因为我选择了eav db design.如果我们不知道产品有哪些名称,请尽可能写查询.
谢谢
有几种方法可以实现这一点.对于每个属性值,这样的事情应该多次连接在表上:
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'
Run Code Online (Sandbox Code Playgroud)
这是小提琴.
以下是使用MAX和GROUP BY的替代方法,我个人更喜欢:
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
Run Code Online (Sandbox Code Playgroud)
祝好运.
| 归档时间: |
|
| 查看次数: |
5127 次 |
| 最近记录: |