这什么都不返回。为什么?

时间:2017-08-16 02:09:16

标签: sql sql-server inner-join where

SELECT 
    Recipes.RecipeID, Recipes.RecipeTitle
FROM 
    Recipes 
INNER JOIN
    Recipe_Ingredients ON Recipes.RecipeID = Recipe_Ingredients.RecipeID 
INNER JOIN
    Ingredients ON Ingredients.IngredientID = Recipe_Ingredients.IngredientID
WHERE 
   (Ingredients.IngredientName = 'Beef') 
   AND (Ingredients.IngredientName = 'Garlic')

此SQL查询不返回任何内容。然而,当我单独/分开检查哪里条件而不将它们与AND放在一起时,他们想出了一个名为“烤牛肉”的食谱,它实际上同时含有牛肉和大蒜。因此,它不应该在结果中显示为1行。但它没有显示任何东西。为什么?

3 个答案:

答案 0 :(得分:4)

它返回NULL,因为一个成分不能同时具有名称。你似乎想要:

SELECT r.RecipeID, r.RecipeTitle
FROM Recipes r INNER JOIN
     Recipe_Ingredients ri
     ON r.RecipeID = ri.RecipeID INNER JOIN
     Ingredients i
     ON i.IngredientID = ri.IngredientID
WHERE i.IngredientName IN ('Beef', 'Garlic')
GROUP BY r.RecipeID, r.RecipeTitle
HAVING COUNT(DISTINCT i.IngredientName) = 2;

答案 1 :(得分:0)

AND在行级别运行。对于同一行,IngredientName不能同时为'Beef'和'Garlic'。您可能需要再次加入Ingredients。

答案 2 :(得分:0)

如果要为同一列选择2个条件,则不能在同一列中使用AND运算符。

SELECT Recipes.RecipeID, Recipes.RecipeTitle
FROM Recipes INNER JOIN
Recipe_Ingredients ON Recipes.RecipeID = Recipe_Ingredients.RecipeID 
INNER JOIN
Ingredients ON Ingredients.IngredientID = Recipe_Ingredients.IngredientID
WHERE (Ingredients.IngredientName in ('Beef' , 'Garlic') )