首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >多属性MySQL产品筛选器

多属性MySQL产品筛选器
EN

Stack Overflow用户
提问于 2015-03-01 10:14:49
回答 2查看 308关注 0票数 0

如何使产品具有所有请求的属性

代码语言:javascript
复制
SELECT * FROM `oc_product_attribute` WHERE (`attribute_id`=15 AND `text`="2500") OR (`attribute_id`=18 AND `text`="24")

此请求,返回如下结果:

代码语言:javascript
复制
|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。我是怎么做到的?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-03-01 10:39:37

代码语言:javascript
复制
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;

我有一种感觉,这个速记否定了索引的使用,但希望您能理解。

票数 1
EN

Stack Overflow用户

发布于 2015-03-01 10:33:38

如果您想匹配多个条件并返回匹配所有条件的值,那么这里有一种方法

代码语言:javascript
复制
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
)
;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28792369

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档