【问题标题】:Mysql Many to Many relation get data with 'and' and 'not' dataMysql多对多关系使用'and'和'not'数据获取数据
【发布时间】:2017-10-24 21:26:09
【问题描述】:

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

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

“不含谷物的三文鱼或鸡肉狗粮”

在此示例中,产品必须具有 Dog 和 Food 属性,可以包含 Salmon 或 Chicken,并且不得包含谷物。

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 匹配,并且没有谷物属性。产品 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

最好的问候,

马丁·巴斯蒂安森

【问题讨论】:

    标签: mysql sql many-to-many


    【解决方案1】:

    您快到了,只需使用not exists 排除您不想要的产品并使用exists 解决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
    

    【讨论】:

    • 如果我们只有'and'关系和'not'关系就可以了,但是我们如何处理查询中'salmon'或'chicken'的'or'语句呢?我已经编辑了问题并处理了一些额外的数据,因此您可以看到查询匹配 2 个产品而不是 1 个
    • @MartijnBastiaansen 立即查看
    猜你喜欢
    • 1970-01-01
    • 2015-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-02
    相关资源
    最近更新 更多