select是否另一个select返回行
我试图做一个select,使烹饪食谱select你有的项目。
我有一个名为ingredientsOwn的表,结构如下:
idType (int) amount (int)
另一个表名为这个结构的食谱 :
idRecipe (int) name (varchar)
另一个表名为recipeIngredients
idRecipe (int) idType (int) amount (int)
我想展示你可以用你有的元素做的食谱,我怎么能做到这一点?
我试图只在一个查询中实现它,因为我真的不知道如何去抛出和arrays的节点js。
谢谢
我想解决这个问题的方法是,尝试为每个配方计算你需要的成分数量,然后join成分数量,如果这两个数字相符,就有一个候选配方。
所以,为了获得配方需要的配料数量,你必须做类似的事情(这更像是一个sql服务器的语法,所以请尝试着重于概念,而不是语法):
select idRecipe, count(*) as neededIngredientsCount from recipeIngredients group by idRecipe
为了获得每种食谱的可用配料的数量,您必须join配料成分,以便能够知道每种配方有多less配料。
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
现在你join之前的两个查询来获得你有足够的配料idRecieps,并join他们的食谱表来获得配方名称。
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语法。
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