我的 mysql 数据库中有一个多对多的表设置,其中包含产品和属性。一个产品可以有许多属性,并且属性可以分配给许多产品。
现在我被困了一段时间,我需要获取一些分配了一些属性但没有分配其他属性的产品。这是一个搜索问题,例如:
“狗粮加鲑鱼或鸡肉,不含 Cereal ”
在此示例中,产品必须具有“狗”和“食品”属性,可以有鲑鱼或鸡肉,并且不能有 Cereal 。
table : product_attributes
+------------+----------------+
| product | attribute |
+------------+----------------+
| Product 1 | Dog |
| Product 2 | Cat |
| Product 3 | Dog |
| Product 1 | Food |
| Product 2 | Food |
| Product 3 | Food |
| Product 1 | Salmon |
| Product 2 | Chicken |
| Product 3 | Salmon |
| Product 1 | Chicken |
| Product 3 | Grain |
| Product 4 | Dog |
| Product 4 | Food |
| Product 4 | Cow |
+------------+----------------+
如果我们选择搜索问题,那么我只希望显示产品 1,因为它与 Dog、Food 和 Salmon/Chicken 匹配,并且没有 Cereal 属性。产品 2 与 Dog 属性不匹配,而产品 3 具有我们不需要的grain 属性。
+------------+
| product |
+------------+
| Product 1 |
+------------+
仅选择真正的“与”关系 Dog & Food 没有问题,但是当我需要在查询中获取“或”关系和“非”关系时,我陷入了困境
select product
from product_attribute
where attribute in ('dog', 'food')
group by product
having count( attribute ) = 2
+------------+
| product |
+------------+
| Product 1 |
+------------+
可以在这里找到包含一些数据的简单 sql fiddle :http://www.sqlfiddle.com/#!9/e2ed09/4
最诚挚的问候,
马丁·巴斯蒂安森
最佳答案
你已经快完成了,只需使用不存在
来排除你不想要的产品,并使用存在
来解决OR
select product
from product_attribute
where attribute in ('dog', 'food') and
not exists(
select 1
from product_attribute pa2
where pa2.product = product_attribute.product and
pa2.attribute in ('grain')
) and
exists(
select 1
from product_attribute pa2
where pa2.product = product_attribute.product and
pa2.attribute in ('salmon', 'chicken')
)
group by product
having count(distinct attribute ) = 2
关于Mysql多对多关系获取 'and'和 'not'数据的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46909520/