【SQL】Oracle的內連線、左外連線、右外連線及全外連線

secooler發表於2010-10-17
理解Oracle的各種連線方法的最有效的方法就是“躬親”,在實踐中去深刻理解內連線,左外連線,右外連線,全外連線的概念的和效果。

1.建立測試表並準備測試資料
sec@ora10g> create table a (a number(1),b number(1),c number(1));
sec@ora10g> create table b (a number(1),d number(1),e number(1));
sec@ora10g> insert into a values(1,1,1);
sec@ora10g> insert into a values(2,2,2);
sec@ora10g> insert into a values(3,3,3);
sec@ora10g> insert into b values(1,4,4);
sec@ora10g> insert into b values(2,5,5);
sec@ora10g> insert into b values(4,6,6);
sec@ora10g> commit;

sec@ora10g> select * from a;

         A          B          C
---------- ---------- ----------
         1          1          1
         2          2          2
         3          3          3


sec@ora10g> select * from b;

         A          D          E
---------- ---------- ----------
         1          4          4
         2          5          5
         4          6          6

2. 內連線
sec@ora10g> select * from a, b where a.a=b.a;
另外一種寫法如下
sec@ora10g> select * from  a inner join b on a.a=b.a;

         A          B          C          A          D          E
---------- ---------- ---------- ---------- ---------- ----------
         1          1          1          1          4          4
         2          2          2          2          5          5

3.左外連線
sec@ora10g> select * from  a,b where a.a=b.a(+);
另外一種寫法如下
sec@ora10g> select *  from  a  left outer join b on a.a=b.a;

         A          B          C          A          D          E
---------- ---------- ---------- ---------- ---------- ----------
         1          1          1          1          4          4
         2          2          2          2          5          5
         3          3          3

4.右外連線
sec@ora10g> select * from  a,b where a.a(+)=b.a;
另外一種寫法如下
sec@ora10g> select * from  a  right outer join b on a.a=b.a;

         A          B          C          A          D          E
---------- ---------- ---------- ---------- ---------- ----------
         1          1          1          1          4          4
         2          2          2          2          5          5
                                          4          6          6
5.全外連線
sec@ora10g> select * from  a full outer join b on a.a=b.a;

         A          B          C          A          D          E
---------- ---------- ---------- ---------- ---------- ----------
         1          1          1          1          4          4
         2          2          2          2          5          5
         3          3          3
                                          4          6          6

6.小結
透過使用Oracle提供的各種SQL連線功能可以解決諸多的“疑難雜症”,需靈活掌握。

Good luck.

secooler
10.10.17

-- The End --

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

相關文章