sql - 通过中间表进行SQL查询

标签 sql join where relational-division

给出下表:

Recipes
| id | name
| 1  | 'chocolate cream pie'
| 2  | 'banana cream pie'
| 3  | 'chocolate banana surprise'

Ingredients
| id | name
| 1  | 'banana'
| 2  | 'cream'
| 3  | 'chocolate'

RecipeIngredients
| recipe_id | ingredient_id
|     1     |      2
|     1     |      3
|     2     |      1
|     2     |      2
|     3     |      1
|     3     |      3

我如何构造一个SQL查询来查找Ingredients.name ='chocolate'和Ingredients.name ='cream'的配方?

最佳答案

这称为关系划分。 here讨论了多种技术。

尚未提供的另一种选择是双重NOT EXISTS

SELECT r.id, r.name
FROM Recipes r
WHERE NOT EXISTS (SELECT * FROM Ingredients i
                  WHERE name IN ('chocolate', 'cream')
                  AND NOT EXISTS
                      (SELECT * FROM RecipeIngredients ri
                       WHERE ri.recipe_id = r.id
                       AND ri.ingredient_id = i.id))

关于sql - 通过中间表进行SQL查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3029454/

相关文章:

c# - EF 6.2 的多个复合索引

python - 使用完全外连接连接 pandas 中的两个数据帧

ruby-on-rails-3 - Ruby on Rails - 如何连接两个表?

arrays - 仅按第一个位置创建蒙版

sql - 最近 3 个月的声明

sql - Azure SQL 数据库与 Azure 移动服务

sql - 显示SQL跟踪(Springboot+Mybatis)

java - Android 中的 SQLITE 获取语句不起作用

java - 查询时间慢 SQL/Java

sql - 是否可以在 SQL 中使用 'Where' 子句仅显示仅包含字母和数字的字段?