查询具有不同值的相同列

时间:2012-08-10 08:42:11

标签: mysql

我刚接触MySql编程,我正在创建一个项目来提升我的技能。  我有一个名为tblRecipe的表,其中包含RecipeId, RecipeName and Instructions列。另一个表名为tblIngredients,其中包含IngredientId,RecipeId, IngredientName列。

现在,例如,RecipeOne需要IngredientOne和IngredientTwo来制作,RecipeTwo需要IngredientOne,IngredientTwo和IngredientThree来制作。 我的程序要求IngredientNames输入,所以当我输入IngredientOne和IngredientTwo它应该给我回到结果RecipeOne。

这是我的代码

Select Recipename,Instructions 
from tblREcipe where RecipeId in 
         (select recipeID 
         from tblIngredients 
         where Ingredientname in('IngredientOne','IngredientTWo')
         );

我知道IN运算符就像是说匹配以下任何一个。 因此,使用该代码,它给了我两个食谱。 我正在寻找相当于AND。 我试过“Ingredientname = ALL(in('IngredientOne','IngredientTwo'))” 但它不会返回任何行。

我可以接受任何更改,例如重组表格,如果这样可以解决问题,因为这只是一个练习项目。希望很快收到你的回复,并提前感谢你。

1 个答案:

答案 0 :(得分:1)

您还需要count与成分数匹配的记录实例数。如下所示:

Select a.Recipename, 
       a.Instructions 
FROM   tblREcipe a INNER JOIN
         (
             SELECT   recipeID,
                      COUNT(IngredientId)
             FROM     tblIngredients 
             WHERE    Ingredientname IN ('IngredientOne', 'IngredientTWo')
             GROUP BY recipeID
             HAVING   COUNT(IngredientId) = 2    -- the number of ingredients
                                                 -- should somehow dynamic
         ) b ON a.recipeID = b.recipeID
相关问题