2017-08-16 95 views
2
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行。但它没有显示任何东西。为什么?这不会返回任何内容。为什么?

+0

请尝试以下 SELECT Recipes.RecipeID,Recipes.RecipeTitle从食谱INNER JOIN Recipe_Ingredients ON Recipes.RecipeID = Recipe_Ingredients.RecipeID INNER JOIN成份ON Ingredients.IngredientID = Recipe_Ingredients.IngredientID WHERE Ingredients.IngredientName = '牛肉'和Ingredients.IngredientName ='大蒜' –

+1

一个配料名称不可能是*牛肉*和*大蒜*在同一时间。当你在句子中使用它时,AND是什么意思? –

+0

在你的where子句中用'或'替换'和' – Milk

回答

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; 
0

AND在行级操作。在同一行中,IngredientsNameName不能同时为'牛肉'和'大蒜'。您可能需要再次加入配料。

0

如果您想为同一列使用IN运算符选择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')) 
相关问题