2015-12-08 52 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),因为他们没有教导解决方案。 –