mysql 多条件匹配,MySQL在与多个条件匹配的一对多关系中苦于查询

博客讨论了如何在MySQL中有效地查询具有多个特定属性的产品。通过使用OR条件和GROUP BY子句,可以找出所有匹配所有条件的产品。另一种方法是使用NOT EXISTS两次,但这在MySQL中可能较为复杂。示例查询找到了同时具有'size=medium'和'colour=blue'的产品。
摘要由CSDN通过智能技术生成

I have two tables which are set out roughly as follows:

products product_attributes

================== ========================================

| id | name | | id | product_id | attribute | value |

================== ========================================

| 1 | product 1 | | 1 | 1 | size | big |

| 2 | product 2 | | 2 | 1 | colour | red |

| 3 | product 3 | | 3 | 2 | size | medium |

| 3 | product 3 | | 4 | 2 | age_range | 3-5 |

| .. | ... | | 5 | 2 | colour | blue |

================== | 6 | 3 | size | small |

| .. | ... | ... | ... |

========================================

There are potentially an infinite amount of attributes for a product which is why they are kept in a separate table.

I want to be able to pull out distinct products which match MULTIPLE (also infinite) attribute conditions but I cant think how to do it without maybe using an OR condition and then some sort of count to check all of the attributes were matched. Im fairly sure this isnt the best way so hopefully someone can help?!

For example find products which have size = 'medium' and colour = 'blue' (this would match product 2 in the example above).

解决方案

The way you suggest with the COUNT is probably the easiest in MySQL

SELECT product_id

FROM product_attributes pa

WHERE (attribute='size' and value='medium')

OR (attribute='colour' and value='blue')

GROUP BY product_id

HAVING COUNT(DISTINCT CONCAT(attribute,value) ) = 2

There is another approach with double NOT EXISTS in the linked article but as MySQL does not support CTEs that would be quite cumbersome.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值