SQL query through an intermediate table

前端 未结 6 1162
孤城傲影
孤城傲影 2020-12-24 03:13

Given the following tables:

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

Ingredients
         


        
6条回答
  •  误落风尘
    2020-12-24 03:25

    This is called relational division. A variety of techniques are discussed here.

    One alternative not yet given is the double 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))
    

提交回复
热议问题