SQL Server内部联接排除结果不起作用
我的数据库中有两个表t_recipe和t_recipe_配料具有1对多的关系意味着一个配方可以有多个配料。我必须把过滤条件,应该给我的食谱,其中包括或排除成分 对于Include,我创建了以下查询,效果良好:SQL Server内部联接排除结果不起作用,sql,sql-server,join,Sql,Sql Server,Join,我的数据库中有两个表t_recipe和t_recipe_配料具有1对多的关系意味着一个配方可以有多个配料。我必须把过滤条件,应该给我的食谱,其中包括或排除成分 对于Include,我创建了以下查询,效果良好: 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
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)
但对于排除在外的配方,我得到的是含有110111成分的配方,但它不应返回它们,我认为这是由于内部连接,包括所有其他成分,也返回配方:
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)
如果你想要不含这些成分的食谱,这里有一种方法:
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;
如果你想要不含这些成分的食谱,这里有一种方法:
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;
请尝试以下操作:
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
请尝试以下操作:
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
我认为你必须用“不存在”来完全排除配方
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
)
我认为你必须用“不存在”来完全排除配方
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
)
设置-不建议在任何地方都使用此选项-恰恰相反@谢谢你格式化这个查询。我已从查询中删除NoLock。现在你能帮我或建议我做错了什么吗?设置-不建议在任何地方都使用它-恰恰相反@谢谢你格式化这个查询。我已从查询中删除NoLock。现在你能帮我一下,或者告诉我我做错了什么。这难道不会产生同样的结果吗?因为你仍然会得到含有这些成分的配方ID,除非这些是配方中唯一的成分。@zlk。不。它只是在寻找那些成分的匹配。这不会产生同样的结果吗?因为你仍然会得到含有这些成分的配方ID,除非这些是配方中唯一的成分。@zlk。不。它只是在寻找这些成分的匹配项。您的答案也很好,但Gordon Linoff的查询执行时间比您的好。感谢您的帮助。您的答案也很好,但Gordon Linoff的查询执行时间比您的好。谢谢你的帮助。