【问题标题】:This returns nothing. Why?这不返回任何内容。为什么?
【发布时间】:2018-01-24 00:52:24
【问题描述】:
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 查询不返回任何内容。然而,当我单独/单独检查 where 条件而不将它们与 AND 放在一起时,他们提出了一个名为“烤牛肉”的食谱,实际上既有牛肉又有大蒜。因此,它不应该在结果中显示为 1 行。但它没有显示任何东西。为什么?

【问题讨论】:

  • 请在下面尝试 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 ' 和 Ingredients.IngredientName = '大蒜'
  • 成分名称不可能同时是牛肉大蒜。 AND在句子中使用时是什么意思?
  • where 子句中将and 替换为or

标签: sql sql-server inner-join where


【解决方案1】:

它返回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;

【讨论】:

    【解决方案2】:

    AND 在行级别进行操作。同一行的成分名称不能同时是“牛肉”和“大蒜”。您可能需要再次加入成分。

    【讨论】:

      【解决方案3】:

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

      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') ) 
      

      【讨论】:

        猜你喜欢
        • 2012-04-02
        • 1970-01-01
        • 2019-09-30
        • 2016-02-19
        • 2021-04-30
        • 2016-11-26
        • 2016-10-12
        • 1970-01-01
        • 2010-09-05
        相关资源
        最近更新 更多