![](/img/trans.png)
[英]Tricky logic problem - how to create a set-based solution for this query?
[英]How to construct a set-based query for a subset?
我有一個以下結構的DB(圖片顯示簡化版)
我應該如何構建一個查詢來獲取那些可以烹飪的食譜,即對於每種食材中的每種成分都需要QUaintity> availableQuantity?
我試過這個:
SELECT r.Name
FROM
Receipe r
JOIN RecipeIngredients ri ON ri.RecipeID = r.Id
JOIN Ingredients i ON i.ID = ri.IngredientsId
WHERE
ri.RequiredQuantity - i.AvailableQuantity > 0
但我不確定這是否正確,因為我認為這只會返回可用的成分。 我應該如何修改上述查詢以僅生成每種成分可用的配方? 謝謝你的幫助
----編輯----
也許是這樣的:
SELECT r.Name
FROM
(
SELECT r.Name AS Name
r.Id AS Id
, CASE (
WHEN (ri.RequiredQuantity - i.AvailableQuantity >= 0)
THEN 1
) AS Available
FROM
Receipe r
JOIN RecipeIngredients ri ON ri.RecipeID = r.Id
JOIN Ingredients i ON i.ID = ri.IngredientsId
WHERE
ri.RequiredQuantity - i.AvailableQuantity >= 0
GROUP BY
r.Id
) AS results
WHERE
// count of ingredients with value 1 for each recipe == count of all required ingredients for this recipe
但是我不知道如何寫上面代碼的最后一行
你現在正在做的是加入配方項目(復制配方數據),然后將復制品分開。 這是一種反模式。 它不會捕獲您的意圖並使查詢更難實現。
重新制定查詢。 你想要的是所有食譜,其中數量條件包含所有項目。 也就是說“不存在條件不成立的項目”。
select *
from recipes r
where not exist (
select *
from RecipeIngredients ri
JOIN Ingredients i ON i.ID = ri.IngredientsId
where
r.id = ri.recipeid --join condition
and not (ri.RequiredQuantity - i.AvailableQuantity >= 0) --quantity condition
)
以下查詢首先獲取所需成分和可用成分的數量。 如果所需成分的數量=可用成分的數量,則選擇配方。
SELECT
R.*
FROM Recipe R
INNER JOIN
(
SELECT
RI.RecipeID,
Count(RI.IngredientsID) Required_Ingredients,
SUM
(CASE
WHEN I.AvailableQuantity > RI.RequiredQuantity THEN 1
ELSE 0
END) Available_Ingredients
FROM RecipeIngredients RI
INNER JOIN Ingredients I ON RI.IngredientsID = I.ID
GROUP BY RI.RecipeID
) Availability
ON R.ID = Availability.RecipeID
WHERE Availability.Required_Ingredients = Availability.Available_Ingredients
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.