我正在嘗試制作一個程式,用戶可以在其中輸入他們在家中擁有的成分,系統會提供他們僅使用這些成分就可以制作的食譜。
制作食譜所需的成分表。'recipe_ingredients'
---------------- --------------- -----------------
| curr_recipe_id | ingredient_id | ingredient_name |
---------------- --------------- -----------------
| 1 | 1 | ingredient 1 |
| 1 | 2 | ingredient 2 |
| 1 | 3 | ingredient 3 |
| 1 | 4 | ingredient 4 |
| 2 | 5 | ingredient 5 |
| 2 | 6 | ingredient 6 |
| 2 | 7 | ingredient 7 |
| 2 | 8 | ingredient 4 |
| 2 | 9 | ingredient 2 |
| 2 | 10 | ingredient 8 |
| 2 | 11 | ingredient 9 |
| 2 | 12 | ingredient 10 |
---------------- --------------- -----------------
食譜表
----------- ----------------------
| recipe_id | name |
----------- ----------------------
| 1 | recipe 1 |
| 2 | recipe 2 |
----------- ----------------------
家里的配料表:'home_ing'
---------------
| home_ing_name |
---------------
| ingredient 1 |
| ingredient 2 |
| ingredient 3 |
| ingredient 4 |
---------------
我想得到所有我能用家里的原料做的食譜。
我應該得到什么作為輸出:
在家中使用成分的可能食譜表:
----------------
| recipe id |
----------------
| 1 |
----------------
我試過使用這個查詢:
select *
from recipes
where recipe_id in (select curr_recipe_id
from recipe_ingredients
where ingredient_name) in (select home_ing_name from home_ing));
此查詢回傳:
----------------
| recipe id |
----------------
| 1 |
| 2 |
----------------
因為我家餐桌上的食材含有配方 2 的其中一種食材。
uj5u.com熱心網友回復:
你可以:
Select recepi_id, MIN(HaveIngredient) from(
Select IR.recepi_id, Case when IH.home_ing_name is null then 0 else 1 end as HaveIngredient
from tableOfInredients IR
Left join tableOfIngredientsAtHome IH
on IR.Ingredient_Name = IH.Home_ing_name) tmp
group by recepi_id
having MIN(HaveIngredient) = 1
第一步是我將我擁有的成分加入收據清單。如果我有成分,如果不是 0,我將標記為 1。
然后我只想每個recepi 有一行,然后選擇recepi_Id,其MIN 值為HaveIngredient 值。在有條款中,我只選擇所有成分都在家里的接收器。
uj5u.com熱心網友回復:
此查詢獲取輸入中提供的成分未滿足的所有 recipe_ingredient 記錄,并從中獲取不在該串列中的所有食譜。
SELECT r.recipe_id
FROM recipe r
WHERE NOT EXISTS(
SELECT * FROM recipe_ingredient ri
WHERE ri.recipe_id = r.recipe_id
AND NOT EXISTS(
/* making the assumption here that the list of ingredients you have is provided
in some form of input that can be placed in temp table or similar */
SELECT * FROM #my_ingredients mi
WHERE mi.ingredient_id = ri.ingredient_id
)
)
這里與另一種方法的主要區別在于,它將回傳沒有任何成分的食譜,這取決于您的要求,可能需要也可能不需要。
uj5u.com熱心網友回復:
SELECT
recipe_id,
name
FROM recipe
WHERE recipe_id NOT IN (
SELECT recipe_id
FROM recipe_ingredients ri
LEFT JOIN home_ing h ON h.home_ing_name = ri.ingredient_name
WHERE home_ing_name IS NULL)
此 SQL 列出了所有沒有 ( NOT IN) 不匹配成分的食譜。子查詢將找到食譜所需的不存在 home_ingredients 的食譜。
見:DBFIDDLE
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/478950.html
