Mysql多对多关系使用'和'和'not'数据获取数据

时间:2017-10-24 11:36:20

标签: mysql sql many-to-many

我的mysql数据库中有很多表设置,包含产品和属性。产品可以有许多属性,属性可以分配给许多产品。

现在我停留了一段时间,我需要获得一些产品,这些产品分配了一些属性,但没有分配其他属性。这是一个搜索问题,如:

“鲑鱼或鸡肉和无谷物的狗粮”

在这个例子中,产品必须具有狗和食物的属性,它可以有三文鱼或鸡肉,并且它必须没有谷物。

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显示,因为它与狗,食物和三文鱼/鸡匹配,并且它没有谷物属性。产品2与Dog属性不匹配,而产品3具有我们不想要的grain属性。

+------------+
|   product  |
+------------+
|  Product 1 |
+------------+

只选择真正的'和'关系狗&食物没问题,但是当我需要在查询中获得'或'关系和'不'关系时我就陷入困境

select product

from product_attribute

where attribute in ('dog', 'food')

group by product

having count( attribute ) = 2


+------------+
|   product  |
+------------+
|  Product 1 |
+------------+

可以在此处找到一个简单的sql,其中包含一些数据:http://www.sqlfiddle.com/#!9/e2ed09/4

最诚挚的问候,

Martijn Bastiaansen

1 个答案:

答案 0 :(得分:0)

您就在那里,只需使用not exists排除您不想要的产品,exists即可解决问题

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