【问题标题】:SQL query to select only results having an exclusive set of related entities from another tableSQL 查询仅选择具有来自另一个表的唯一相关实体集的结果
【发布时间】:2018-04-03 16:33:56
【问题描述】:

我有一个包含 2 个表的关系数据库,比如说 paintingscolors。它们通过数据透视表color_painting处于多对多关系。

“绘画”表:

id  name
---------------------
1   Lion and cubs
2   Sunset in Ontario

“颜色”表:

id  color
---------------------
1   grey
2   yellow
3   orange

“color_painting”表:

painting_id  color_id
---------------------
1            1
1            2
2            1
2            2
2            3

因此,绘画与颜色的关联如下:

Lion and cubs”链接到颜色“grey”和“yellow

Sunset in Ontario”链接到“grey”、“yellow”和“orange

如何编写一个 SQL 查询来选择其中只有特定颜色而没有其他颜色的画作?

例如我想要只有“灰色”和“黄色”的画作。因此,查询应该返回“Lion and cubs”绘画而不是“Sunset”,因为“Sunset”也有“orange”。

是否可以使用一个查询? (SQL 应该在 MySQL、SQLite、PostgreSQL 和 SQL Server 方言上运行)。

【问题讨论】:

  • 从 MySQL、SQL Server & Postgresql、sqlite 中任选其一。
  • 你真的在使用所有这些产品吗?`
  • 向我们展示您当前的查询尝试。还有预期的结果(具有已经指定的表数据。)
  • 我正在编写一个允许可替换存储引擎的框架。

标签: mysql sql sql-server postgresql sqlite


【解决方案1】:

使用NOT INNOT EXISTS 排除不同颜色的画作,其余画作必须有2行才能对应您的需求。

select p.id, p.name
from paintings p
join color_painting cp on p.id = cp.painting_id  
where p.id not in
    (
       select painting_id 
       from color_painting cp 
       join colors c on cp.color_id = c.id and c.color not in ('yellow','grey')
    )
group by p.id, p.name
having count(*) = 2

【讨论】:

  • 感谢您的回答,它非常有效,如果可以的话,我会接受这两个答案,但我必须做出选择,我接受了另一个答案,原因有几个:-“解释" 在那里显示了一个更短的执行计划,3 步对 4 步; - “exists”将在找到第一个匹配项后停止,而“in”将不得不拉整个行集; - 它出现在几分钟前除此之外,我真的很喜欢你回答中“有”子句的优雅,我会使用你回答的那部分
【解决方案2】:

要检查是否使用了所有需要的颜色,请计算使用了多少颜色:

SELECT *
FROM paintings
WHERE (SELECT COUNT(*)
       FROM color_painting
       WHERE painting_id = paintings.id
         AND color_id IN (1, 2)
      ) = 2
  AND NOT EXISTS (SELECT *
                  FROM color_painting
                  WHERE painting_id = paintings.id
                    AND color_id NOT IN (1, 2));

【讨论】:

  • 看起来很完美。
猜你喜欢
  • 2017-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-23
相关资源
最近更新 更多