【发布时间】:2020-02-23 19:15:43
【问题描述】:
我的子查询过滤掉了太多结果。它应该在子查询中过滤掉 3 个配方中使用的 12 种成分。共有 79 种成分,因此查询应返回 67 行。目前我的查询返回 54。
我不确定为什么,但是如果我将第二个 WHERE 条件更改为 OR 而不是 AND,我会得到 68 行,这与我的预期相差无几
我正在尝试创建的查询:
(5) 找出爱尔兰炖菜中未使用的所有成分的 ID 和名称, Pollo Picoso,或烤牛肉。 (2 列,67 行)
select distinct Recipes.RecipeID, Ingredients.IngredientName
from Recipes
inner join Recipe_Ingredients on Recipes.RecipeID = Recipe_Ingredients.RecipeID
inner join Ingredients on Recipe_Ingredients.IngredientID = Ingredients.IngredientID
where Ingredients.IngredientID NOT IN
(select distinct Ingredients.IngredientID
from Recipes
join Recipe_Ingredients on Recipes.RecipeID = Recipe_Ingredients.RecipeID
join Ingredients on Recipe_Ingredients.IngredientID = Ingredients.IngredientID
where Recipes.RecipeTitle = 'Roast Beef')
and Ingredients.IngredientID NOT IN
(select distinct Ingredients.IngredientID
from Recipes
join Recipe_Ingredients on Recipes.RecipeID = Recipe_Ingredients.RecipeID
join Ingredients on Recipe_Ingredients.IngredientID = Ingredients.IngredientID
where Recipes.RecipeTitle = 'Irish Stew')
and Ingredients.IngredientID NOT IN
(select distinct Ingredients.IngredientID
from Recipes
join Recipe_Ingredients on Recipes.RecipeID = Recipe_Ingredients.RecipeID
join Ingredients on Recipe_Ingredients.IngredientID = Ingredients.IngredientID
where Recipes.RecipeTitle = 'Pollo Picoso');
【问题讨论】:
-
首次使用
not exists -
查找所有成分的 ID 和名称如果您只需要成分,为什么要选择
Recipes.RecipeID?
标签: sql sql-server tsql join left-join