2016-08-19 29 views
0

它有2個表是這樣的:以找到那些記錄包含所有用逗號分隔的標識的SQL服務器的列表

t_recipe

RecipeId  Name    InsertDate 
---------------------------------------------- 
1    Mutton   9/6/2015 0:00 
2    Veg Biryani  9/5/2015 0:00 

t_recipe_ingredient

RecipeId  IngrId   InsertDate 
---------------------------------------------- 
1    200    9/6/2015 0:00 
1    201    9/5/2015 0:00 
1    101    9/4/2015 0:00 
1    103    9/3/2015 0:00 
2    100    9/2/2015 0:00 
2    500    9/6/2015 0:00 
2    202    9/5/2015 0:00 
2    200    9/4/2015 0:00 

現在,當我正在使用以下查詢:

select * 
from t_recipe r 
    join t_recipe_ingredient i ON r.RecipeID = i.RecipeId 
where i.IngrId in (200, 201) 

我得到了兩個食譜的輸出,但它應該給我只有羊肉,因爲它是包含這兩種成分的。看起來好像我的查詢至少檢查了一場比賽,但是我希望它只返回包含in子句中所有成分的配方。

+1

我想你已經得到了你,因爲他們都錯了樣本數據似乎爲行201和200組。 –

+0

添加預期結果! – jarlh

回答

3

你需要按你的食譜,並採取只有那些既成分

select r.RecipeId, r.Name, r.InsertDate 
from t_recipe r 
join t_recipe_ingredient i ON r.RecipeID = i.RecipeId 
where i.IngrId in (200,201) 
group by r.RecipeId, r.Name, r.InsertDate 
having count(distinct i.IngrId) = 2 
相關問題