例如,有一张带有商品属性的表格。每个产品可以有多个相同属性的值。
商品
goods_id | property | value
1 |color | red
1 |size | 100
1 |size | 200
2 |color | red
2 |color | green
2 |size | 200
如果我需要找到所有颜色为红色且大小为100的项目,那么我运行以下查询:
SELECT goods_id FROM goods
WHERE (property = 'color' AND value = 'red') OR
(property = 'size' AND value = '100')
GROUP BY goods_id
HAVING COUNT(goods_id) = 2
MYSQL 返回goods_id = 1
但是,如果我需要查找所有颜色为红色或绿色且大小为100的项目,请使用以下查询
SELECT goods_id FROM goods
WHERE (property = 'color' AND value IN ('red', 'green')) OR
(property = 'size' AND value = '100')
GROUP BY goods_id
HAVING COUNT(goods_id) = 2
返回 ids 1 AND 2,但应该只有 1。
如何更改第二个查询以返回正确的结果?感谢您的任何建议