MySQL 按多个属性筛选产品
MySQL Product filters by multiple attributes
如何获取产品的所有请求属性
SELECT * FROM `oc_product_attribute` WHERE (`attribute_id`=15 AND `text`="2500") OR (`attribute_id`=18 AND `text`="24")
本次请求,返回结果如下:
|product_id | attribute_id | language_id | text
+-----------+--------------+-------------+-----
|1 | 15 | 1 | 2500
|2 | 15 | 1 | 2500
|3 | 15 | 1 | 2500
|4 | 15 | 1 | 2500
|3 | 18 | 1 | 24
|4 | 18 | 1 | 24
但我只需要产品 3 和 4,因为它们有 15=2500 和 18=24。我该怎么做?
如果你想匹配多个条件并且return值匹配所有条件这里是一种方法
select p1.* from oc_product_attribute p1
where
p1.`attribute_id`=15 AND p1.`text`='2500'
and exists
(
select 1 from oc_product_attribute p2
where
p2.attribute_id = 18
and p2.text = 24
and p1.product_id = p2.product_id
)
union all
select p1.* from oc_product_attribute p1
where
p1.`attribute_id`=18 AND p1.`text`='24'
and exists
(
select 1 from oc_product_attribute p2
where
p2.attribute_id = 15
and p2.text = 2500
and p1.product_id = p2.product_id
)
;
SELECT product_id
FROM oc_product_attribute
WHERE (attribute_id,text) IN ((15,'2500'),(18,'24'))
GROUP
BY product_id
HAVING COUNT(DISTINCT attribute_id,text) = 2;
我觉得这 shorthand 否定了索引的使用,但希望你明白了。
如何获取产品的所有请求属性
SELECT * FROM `oc_product_attribute` WHERE (`attribute_id`=15 AND `text`="2500") OR (`attribute_id`=18 AND `text`="24")
本次请求,返回结果如下:
|product_id | attribute_id | language_id | text
+-----------+--------------+-------------+-----
|1 | 15 | 1 | 2500
|2 | 15 | 1 | 2500
|3 | 15 | 1 | 2500
|4 | 15 | 1 | 2500
|3 | 18 | 1 | 24
|4 | 18 | 1 | 24
但我只需要产品 3 和 4,因为它们有 15=2500 和 18=24。我该怎么做?
如果你想匹配多个条件并且return值匹配所有条件这里是一种方法
select p1.* from oc_product_attribute p1
where
p1.`attribute_id`=15 AND p1.`text`='2500'
and exists
(
select 1 from oc_product_attribute p2
where
p2.attribute_id = 18
and p2.text = 24
and p1.product_id = p2.product_id
)
union all
select p1.* from oc_product_attribute p1
where
p1.`attribute_id`=18 AND p1.`text`='24'
and exists
(
select 1 from oc_product_attribute p2
where
p2.attribute_id = 15
and p2.text = 2500
and p1.product_id = p2.product_id
)
;
SELECT product_id
FROM oc_product_attribute
WHERE (attribute_id,text) IN ((15,'2500'),(18,'24'))
GROUP
BY product_id
HAVING COUNT(DISTINCT attribute_id,text) = 2;
我觉得这 shorthand 否定了索引的使用,但希望你明白了。