![](/img/trans.png)
[英]SQL 2008 stored proc returns nothing if CROSS APPLY is nothing. How can I fix?
[英]This returns nothing. Why?
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行。 但是它什么也沒顯示。 為什么?
它返回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;
AND在行級別運行。 對於同一行,IngredientName不能同時是'Beef'和'Garlic'。 您可能需要重新加入配料。
如果要為同一列選擇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') )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.