理解full outer jion,union,union all

531968912發表於2016-09-14
準備兩張測試表
09:41:52 kiwi@storedb1> select * from t1;


          ID1 I
------------- -
            1 A
            2 B
            3 C


Elapsed: 00:00:00.00
09:41:56 kiwi@storedb1> select * from t2;


I ID
- --
A A2
B B2
D D2


我們先來看看full outer join
09:42:14 kiwi@storedb1> select t1.id1,t1.id2,t2.id3 from t1 full outer join t2 on(t1.id2=t2.id2);


          ID1 I ID
------------- - --
            1 A A2
            2 B B2
                D2
            3 C
            
再來看看union
09:44:54 kiwi@storedb1>  select t1.id1,t1.id2,t2.id3 from t1 left outer join  t2 on(t1.id2=t2.id2)
09:45:09   2  union
09:45:18   3   select t1.id1,t1.id2,t2.id3 from t1 right outer join  t2 on(t1.id2=t2.id2);


          ID1 I ID
------------- - --
            1 A A2
            2 B B2
            3 C
                D2


看看 union all
  1   select t1.id1,t1.id2,t2.id3 from t1 left outer join  t2 on(t1.id2=t2.id2)
  2  union all
  3*  select t1.id1,t1.id2,t2.id3 from t1 right outer join  t2 on(t1.id2=t2.id2)
09:46:20 kiwi@storedb1> /


          ID1 I ID
------------- - --
            1 A A2
            2 B B2
            3 C
            1 A A2
            2 B B2
                D2


從中我們就可以看出區別full outer join 相當於分別做left outer join,right outer join 然後做一個union
union 是兩個的交集不包括重複的行,預設進行排序
而union all的效果是left outer join和right outer join的交集,包括了重複的集合,不進行排序

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/25462274/viewspace-2124997/,如需轉載,請註明出處,否則將追究法律責任。

相關文章