【问题标题】:MySQL Product filters by multiple attributesMySQL Product 按多个属性过滤
【发布时间】:2015-03-01 10:14:49
【问题描述】:

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

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。我是怎么做到的?

【问题讨论】:

  • 您已经知道如何使用WHERE 子句,但您不知道如何为product_id 添加过滤器?
  • @Tom 那会是什么过滤器?
  • @Strawberry,这是产品属性表,我通过返回的产品 id 得到过滤的产品。我的问题不完全理解。但无论如何,感谢您的帮助。我达到了预期的结果。

标签: mysql filter


【解决方案1】:
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;

我觉得这种速记否定了索引的使用,但希望你明白这一点。

【讨论】:

  • 如果第一行 SELECT DISTINCT product_id AS product_id 和最后一行 HAVING COUNT(product_id) = 2 这似乎有效,但我不确定。
  • 好吧,你还没有向我们展示你的架构/数据集,所以只有你可以知道
【解决方案2】:

如果要匹配多个条件,返回值匹配所有条件这里是一种方法

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
)
;

【讨论】:

  • 好,是否可以通过 product_id 区分来执行这样的请求?
  • 完全不同只会返回每个标准中的一种产品。
猜你喜欢
  • 1970-01-01
  • 2014-09-15
  • 1970-01-01
  • 2021-03-17
  • 2012-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-27
相关资源
最近更新 更多