假设我们有3个表:产品,属性和详细信息。
产品
id name price
1 pr1 120
2 pr2 140
3 pr3 200
4 pr4 165
属性
id name
1 color
2 guarantee
3 resolution
4 year
5 contrast ratio
详情
id productId attributeId value
1 1 1 grey
2 1 2 yes
3 2 1 black
4 2 4 2011
5 2 5 70 000:1
6 4 2 no
并希望例如选择color = black,year = 2011和对比度= 70 000:1的所有产品。在这个例子中,结果将是id = 2的产品。那将是什么mysql语法?
SELECT * FROM products, details WHERE products.id = details.productId
AND details.attributeId = 1 (For the first attribute)
AND details.attributeId = 4 (For the second and third attribute?)
...
答案 0 :(得分:0)
使用
SELECT *
FROM products p
INNER JOIN (SELECT * FROM details d WHERE d.attributeId = 1 ) d1 ON p.ID = d1.productid
INNER JOIN (SELECT * FROM details d WHERE d.attributeId = 4 ) d4 ON p.ID = d4.productid
INNER JOIN (SELECT * FROM details d WHERE d.attributeId = 5 ) d5 ON p.ID = d5.productid
WHERE
d1.value = 'black' AND
d4.value = '2011' AND
d5.value = '70 000:1'