2016-01-11 89 views
1

如何将两个表连接在一起以获取所有行,然后输入NULL,其中一个在另一个中缺失。左/右连接以接收所有行

例如:

declare @t1 table (x int) 
declare @t2 table (x int) 

insert into @t1 select 2 
insert into @t1 select 3 
insert into @t1 select 4 
insert into @t1 select 5 

insert into @t2 select 1 
insert into @t2 select 2 
insert into @t2 select 5 

select * 
from @t1 t1 
left join @t2 t2 on t2.x = t1.x 

结果应该是这样的:

t1.x t2.x 
NULL 1 
2  2 
3  NULL 
4  NULL 
5  5 
+2

['FULL OUTER JOIN'](http://stackoverflow.com/questions/34719640/left-right-join-to-receive-all-rows) –

回答

2
select * 
from @t1 t1 
full outer join @t2 t2 on t2.x = t1.x 

这就像左连接,但即使有将采取所有记录从两个表没有匹配,并且在没有匹配时输入null。

+0

使用全外连接 –

+0

谢谢你们就是这样! – Avithohol

2
select * 
from @t1 t1 
FULL OUTER join @t2 t2 on t2.x = t1.x 
2

这两个表中的所有行都在完整的外连接中返回。 SQL Server将以下ISO关键字用于FROM子句中指定的外部联接:LEFT OUTER JOIN或LEFT JOIN。 RIGHT OUTER JOIN或RIGHT JOIN。 FULL OUTER JOIN或FULL JOIN