【问题标题】:SQL Server Inner join exclude results not workingSQL Server 内连接排除结果不起作用
【发布时间】:2016-08-16 05:10:58
【问题描述】:

我的数据库中有 2 个表 t_recipe 和 t_recipe_ingredient 具有一对多的关系意味着一个食谱可以有多种成分。我必须设置一个过滤条件,它应该给我包含或排除成分的食谱。

对于包含我在下面创建的查询,它工作正常:

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)    

【问题讨论】:

  • 设置Bad Habits to kick - putting NOLOCK everywhere - 不建议在任何地方使用它 - 恰恰相反!
  • @marc_s:感谢您格式化查询。我已从查询中删除了 NoLock。现在你能帮我或建议我做错了什么。

标签: sql sql-server join


【解决方案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 
   )

【讨论】:

  • 您的答案也可以正常工作,但 Gordon Linoff 的查询执行时间比您的要好。感谢您的帮助。
【解决方案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;

【讨论】:

  • 这不会产生相同的结果吗?因为您仍然会获得包含这些成分的配方 ID,除非这些是配方中唯一的成分。
  • @zlk 。 . .不。它只是在这些成分上寻找匹配项。
【解决方案3】:

尝试以下方法:

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   

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-03
    • 1970-01-01
    • 2020-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-25
    相关资源
    最近更新 更多