如何从两个SQL表中获取不匹配的记录?

Pra*_*ant 5 sql

我想从SQL中的两个表中获取不匹配的记录,表结构如下:

表格1

Id      Name
1       Prashant
2       Ravi
3       Gaurav
5       Naween
7       Sachin
Run Code Online (Sandbox Code Playgroud)

表2

Id      Name
1       Prashant
2       Ravi
4       Alok
6       Raja
Run Code Online (Sandbox Code Playgroud)

我想要的输出是

Id      Name
3       Gaurav
4       Alok
5       Naween
6       Raja
7       Sachin
Run Code Online (Sandbox Code Playgroud)

在SQL中获取所需输出的查询是什么?

bri*_*gge 10

我认为joeslice的回答只会给出一半的结果.你需要联合另一个表.或者,您可以执行完全外部联接.

select a.Id, a.Name from Table1 a left outer join Table2 b on a.Name = b.Name where b.Id is null
UNION ALL
select a.Id, a.Name from Table2 a left outer join Table1 b on a.Name = b.Name where b.Id is null
Run Code Online (Sandbox Code Playgroud)

  • 请记住,这比完全外部联接更昂贵. (3认同)

Sam*_*ron 5

create table #t1 (Id int, name varchar(50)) 
create table #t2 (Id int, name varchar(50)) 

insert #t1 values (1,       'Prashant')
insert #t1 values (2,      'Ravi')
insert #t1 values (3,       'Gaurav')
insert #t1 values (5,       'Naween')
insert #t1 values (7,       'Sachin')

insert #t2 values (1,       'Prashant')
insert #t2 values (2,       'Ravi')
insert #t2 values (4,       'Alok')
insert #t2 values (6,       'Raja')

select isnull(#t1.id, #t2.id), isnull(#t1.name,#t2.name)  from #t1 
full outer join #t2 on #t1.id = #t2.id
where #t2.Id is null or #t1.id is null
Run Code Online (Sandbox Code Playgroud)

结果:

3   Gaurav
5   Naween
7   Sachin
4   Alok
6   Raja


Ras*_*dit 5

Select Id, Name
from Table1
where Id not in (select Id from Table2)
UNION 
Select Id, Name
from Table2
where Id not in (select Id from Table1)
Run Code Online (Sandbox Code Playgroud)