首页 > 解决方案 > SQL,判断表A中的记录是否存在于表B中

问题描述

TableA 有 AccountNum 和 RoutingNum 列

TableB 也有列 AccountNum 和 RoutingNum

表 B 更值得信赖。因此,我想查找表 A 中的所有记录是否都存在于表 B 中。如果不存在,哪些记录不匹配。

这是在正确的轨道上吗?您的解决方案将不胜感激。

select * 
from TableA a 
where a.AccountNum not in (select b.AccountNum from TableB)

标签: sql

解决方案


您可以使用not exists. 以下查询为您提供了在tablea中找不到的所有记录tableb

select a.*
from tablea a
where not exists (
    select 1 
    from tableb b 
    where a.accountNum = b.accountNum and a.routingNum = b.routingNum
)

这假设您希望在两列上都匹配(这是您的描述所暗示的)。您可以调整where子查询中的条件以仅匹配一列。


推荐阅读