使用NOT EXISTS过滤重复行结果不符,如何实现全列匹配?
筛选与目标表全列无重叠的行
你当前的NOT EXISTS语句仅过滤了Id和Name完全匹配的组合,所以会返回所有TB1中没有相同(Id,Name)配对的记录,但你需要的是TB2中Id从未在TB1出现、且Name也从未在TB1出现的行,也就是整行的两个字段都和TB1无任何重叠。
解决方案1:使用NOT IN
select b.Id, b.Name from TB2 as b where b.Id not in (select Id from TB1) and b.Name not in (select Name from TB1)
解决方案2:使用NOT EXISTS(避免NULL值影响)
select b.Id, b.Name from TB2 as b where not exists (select 1 from TB1 where Id = b.Id) and not exists (select 1 from TB1 where Name = b.Name)
这两种写法都会精准返回你需要的(4, 'Mob'),因为该行的Id和Name都未在TB1的对应列中出现过。
内容的提问来源于stack exchange,提问作者Slowcode_beef
相关产品推荐
相关产品推荐

