繁体   English   中英

Sql 查询帮助从两个表中获取不匹配的记录

[英]Sql Query help to get non matching records from two tables

我正在尝试从 2 个表中获取不匹配的记录

例如

TableA
 ID           Account
 1               Acc1
 2               Acc2
 3               Acc3

 TableB
 Opp          Accountid
 Opp1            1
 Opp2            2
 Opp3            4

我需要知道 TableB 中存在哪个 accountid,但 TableA 中没有。 如果有人可以提供此查询,那就太好了。

所需记录将是 tableB 的 Opp3

谢谢

普拉迪

create table #one (id int,acc nvarchar(25))
insert into #one (id , acc) values(1,'one') 
insert into #one (id , acc) values(2,'two') 
insert into #one (id , acc) values(3,'three') 

create table #two (acct nvarchar(25),ids int)
insert into #two (acct,ids) values('one',1) 
insert into #two (acct,ids) values('two',3) 
insert into #two (acct,ids) values('four',4) 

select ids from #two EXCEPT select id from #one 

drop table #one 
drop table #two 

测试这个

SELECT B.Accountid 
  FROM TableB AS B 
  LEFT 
  JOIN TableA AS A 
    ON A.ID = B.Accountid 
 WHERE A.ID IS NULL;

LEFT JOIN 意味着它从第一个表中获取所有行 - 如果第一个连接条件没有匹配项,则表 B 的结果表列将为 null - 这就是它起作用的原因。

SELECT B.Accountid
FROM TableB AS B 
LEFT JOIN TableA AS A ON A.ID = B.Accountid 
WHERE A.ID IS NULL

尝试这个

(select * from t1
except 
select * from t2)

union

(select * from t2
except 
select * from t1)

认为您在两个表中的列数相同

上面提到的查询 select 来自 #two 的 ID 除了来自 #one 的 select id 只会给你来自 #two 的不匹配行。 它会忽略#one

这将产生相同的结果。

select * from TableB where Accountid not in (select ID from TableA)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM