选择是否另一个选择返回行

时间:2015-12-08 03:53:40

标签: mysql node.js

我试图选择在您拥有的物品中选择烹饪食谱。

我有一个名为 ingredientsOwn 的表格,其结构如下:

idType (int) amount (int)

另一个名为食谱的表格具有以下结构:

idRecipe (int) name (varchar)

另一个名为 recipeIngredients

的表格
idRecipe (int) idType (int) amount (int)

我想展示你可以用你拥有的元素做的食谱,我怎么能这样做?

我试图在一个查询中实现它,因为我真的不知道怎么去节点js上的throw和数组。

由于

2 个答案:

答案 0 :(得分:1)

我想解决这个问题的方法是,尝试计算每个食谱,你需要的食材数量,并加上你自己的成分数量,如果两个数字匹配,你就有一个候选配方。 / p>

因此,要获得配方需要的成分数量,您必须做类似的事情(这更像是一个sql server语法,所以请尝试专注于概念,而不是语法):< / p>

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

要获得每个食谱的可用成分数量,您必须将recipeOwn与recipeIngredients一起加入,以便能够告诉您每种食谱有多少匹配成分。

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

现在您加入前两个查询以获取您有足够成分的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语法。

答案 1 :(得分: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