我有一个表格,其中包含我的产品详细信息
+-----+------------+--------+-------+---------+
| id | product_id | cat_id | field | value |
+-----+------------+--------+-------+---------+
| 166 | 121 | 12 | model | Core i7 |
| 164 | 121 | 12 | brand | Intel |
| 172 | 15 | 12 | model | Core i5 |
| 170 | 15 | 12 | brand | Intel |
+-----+------------+--------+-------+---------+
4 rows in set
现在,我想编写一个查询,让我在以下情况下获得product_id:
我已经尝试过了,但是它没有返回任何行,我想我应该使用JOIN。
SELECT * FROM `wp_product_details_fields`
WHERE `field` = 'brand' AND `value` = 'Intel' AND `field` = 'model' AND `value` = 'Core i7'
答案 0 :(得分:1)
使用group by
和having
:
select product_id
from wp_product_details_fields
where field in ('model', 'brand')
group by product_id
having max(field = 'model' and value = 'Core i7') = 1
and max(field = 'brand' and value = 'Intel' ) = 1
或者更好,使用元组相等:
select product_id
from wp_product_details_fields
where (field, model) in ( ('model', 'Core i7'), ('brand', 'Intel') )
group by product_id
having count(*) = 2
答案 1 :(得分:0)
使用OR
您应该尝试如下操作:
SELECT * FROM `wp_product_details_fields`
WHERE (`field` = 'brand' AND `value` = 'Intel') OR (`field` = 'model' AND `value` = 'Core i7')
答案 2 :(得分:0)
我认为您必须重新考虑您的数据库结构,我建议您拥有模型领域和品牌领域。因此您可以执行简单的“选择”查询。并过滤行。