2012-08-10 75 views
1

我只是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

您還需要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 
+0

謝謝我試過了,它工作。 – user1589687 2012-08-12 07:57:52

相關問題