2016-08-16 28 views
1

我在我的數據庫中有2個表t_recipe和t_recipe_ingredient具有1對多關係表示一個配方可以有多個成分。我必須把過濾條件,應該給我的食譜,其中包括成分包括或排除在外。SQL Server內部聯接排除結果不起作用

對於包括我在下面的查詢創建工作得很好:

select * 
from t_recipe r 
join t_recipe_ingredient rexc ON r.RecipeID = rexc.RecipeID 
where r.RecipeTypeID = 1 
    and rexc.IngrId in (110, 111)  

但排除我得到具有成分110,111食譜但是它不應該回報他們,我認爲這是由於內部連接這是包括所有的其他成分也和返回食譜:

select * 
from t_recipe r 
join t_recipe_ingredient rexc WITH (NOLOCK) ON r.RecipeID = rexc.RecipeID 
where r.RecipeTypeID = 1 
    and rexc.IngrId not in (110, 111)  
+0

集[壞習慣踢 - 把NOLOCK無處不在(HTTP:// blogs.sqlsentry.com/aaronbertrand/bad-habits-nolock-everywhere/) - 不推薦*在任何地方使用它 - 完全相反! –

+0

@marc_s:感謝您格式化查詢。我從查詢中刪除了NoLock。現在你能幫我或者告訴我我做錯了什麼。 – ChupChapCharli

回答

2

如果不想這些成分配方,這裏是一個方法:

select r.* 
from t_recipe r left join 
    t_recipe_ingredient rexc 
    on r.RecipeID = rexc.RecipeID and rexc.IngrId in (110, 111) 
where r.RecipeTypeID = 1 and rexc.RecipeID is null; 
+0

這不會產生相同的結果嗎?因爲你仍然會得到含有這些成分的食譜ID,除非這些成分是食譜中唯一的成分。 – ZLK

+0

@zlk。 。 。不,它只是在尋找配料。 –

0

嘗試以下操作:

select * 
from t_recipe r 
join t_recipe_ingredient rexc WITH (NOLOCK) ON r.RecipeID = rexc.RecipeID AND rexc.IngrId not in (110, 111)  
where r.RecipeTypeID = 1 
3

我認爲你必須使用不完全以排除配方存在

select * from t_recipe r 
    where r.RecipeTypeID = 1 
    and not exists(
    select null 
    from t_recipe_ingredient 
    where ingrid in(110, 111) and r.RecipeID = rexc.RecipeID 
    ) 
+0

您的答案也可以正常工作,但Gordon Linoff的查詢執行時間比您的要好。謝謝你的幫助。 – ChupChapCharli