2015-12-08 116 views
1

我試圖做一個選擇,使烹飪食譜選擇你的項目。選擇是否有其他選擇返回行

我有一個名爲ingredientsOwn結構如下表:

idType (int) amount (int) 

命名食譜這種結構的另一個表:

idRecipe (int) name (varchar) 

,並命名爲另一個表recipeIngredients

idRecipe (int) idType (int) amount (int) 

我想展示你可以用你有的元素做的食譜,我怎麼能做到這一點?

我試圖只在一個查詢中實現它導致我真的不知道如何去拋出和數組在節點js上。

感謝

回答

1

的方式,我會去解決這個就是嘗試計算每個配方,你需要成分的數量,並加入與原料本身的數量,如果兩個號碼匹配,你有一個候選配方。

因此,要獲得配方需要的配料數量,您必須執行類似操作(這更像是SQL Server語法,因此請嘗試專注於概念,而不是語法):

select idRecipe, count(*) as neededIngredientsCount 
from recipeIngredients 
group by idRecipe 

要獲得每種食譜的可用配料數量,您必須加入配料配方中的配料成分,以便能夠說明每種配方有多少配料。

select ingredientsOwn.idRecipe, count(*) as matchingIngredientsCount 
from ingredientsOwn inner join recipeIngredients 
on ingredientsOwn.idType = recipeIngredients.idType 
where ingredientsOwn.amount >= recipeIngredients.amount 
group by ingredientsOwn.idRecipe 

現在你加入前2個查詢來獲得你有足夠成分idRecieps,並與配方表加入他們拿到配方名稱。

select r.idRecipe, r.name from 
((select idRecipe, count(*) as neededIngredientsCount 
from recipeIngredients 
group by idRecipe) as in 
inner join 
(select ingredientsOwn.idRecipe, count(*) as matchingIngredientsCount 
from ingredientsOwn inner join recipeIngredients 
on ingredientsOwn.idType = recipeIngredients.idType 
where ingredientsOwn.amount >= recipeIngredients.amount 
group by ingredientsOwn.idRecipe) as io 
on in.idRecipe = io.idRecipe 
    and in.neededIngredientsCount = io.matchingIngredientsCount 
inner join 
(select * from recipes) as r 
on r.idRecipe = in.idRecipe) 

希望這會有所幫助,並抱歉無法提供有效的mysql語法。

+0

它的工作!謝謝! –

0
SELECT * FROM recipes INNER JOIN (
    select idRecipe from recipeIngredients 
    WHERE recipeIngredients.idType IN (
     SELECT ingredientsOwn.idType from ingredientsOwn 
    ) 
) as a ON a.idRecipe = recipes.idRecipe 
+0

您能否請[編輯]解釋爲什麼這段代碼回答這個問題?僅限代碼答案[阻止](http://meta.stackexchange.com/q/148272/274165),因爲他們沒有教導解決方案。 –