將FULL JOIN改為UNION ALL


有時候,我們需要得到全連接的效果,如下例:

 

create table t1 (id1 int, name1 varchar(20))

create table t2 (id2 int, name2 varchar(20))

insert into t1 values(1,'a')
insert into t1 values(2,'b')

insert into t2 values(1,'c')
insert into t2 values(3,'d')

我們想得到如下結果:

1   a   c

2   b

3       d

對於這種需求,理所當然地想到全連接FULL JOIN:

 

select
case when  t1.id1 is null then t2.id2 else t1.id1 end as id,
name1,name2
from t1
full join t2
on t1.id1=t2.id2

 

 但是全連接的效率較差,可以改為:

select id1,max(name1) name1,max(name2) name2
from
(
select id1,name1,'' as name2 from t1
union all
select id2,'' as name1,name2 from t2
) t
group by id1
 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM