資料庫中涉及兩個表之間的資料查詢通常使用連線的方法實現。連線分為內連線和外連線。
內連線:
指連線結果僅包含符合連線條件的行,參與連線的兩個表都應該符合連線條件。外連線:
連線結果不僅包含符合連線條件的行同時也包含自身不符合條件的行。包括左外連線、右外連線和全外連線。左外連線:
左邊表資料行全部保留,右邊表保留符合連線條件的行
右外連線:
右邊表資料行全部保留,左邊表保留符合連線條件的行
全外連線:
左外連線 union 右外連線
例子:
資料庫版本:oracle 9i
表testa,testb,testc,各有a, b兩列 a
b001
10a
00220a
a b
001
10b003
30b
a b
001
10c004
40c
連線分為兩種:內連線與外連線。
a.內連線
內連線,即最常見的等值連線,例:
select*
fromtesta,testb
wheretesta.a=testb.a結果
a b
a b
001
10a
001
10b
b.外連線
外連線分為左外連線,右外連線和全外連線。
1.左外連線left outer join 或者 left join
左外連線就是在等值連線的基礎上加上主表中的未匹配資料,例:
select*
fromtesta
left outer jointestb
ontesta.a=testb.a
oracle 支援另一種寫法
select*
fromtesta,testb
wheretesta.a=testb.a(+)
結果: a
b a
b 001
10a
001
10b
00210b
三個表做左外連線
select*
fromtesta
left outer jointestb
ontesta.a=testb.a
left outer jointestc
ontesta.a=testc.a
oracle 支援的另外一種寫法
select*
fromtesta,testb,testc
wheretesta.a=testb.a(+)
andtesta.a=testc.a(+)
結果: a
b ab a
b001
10a
001
10b
001
10c002
20a
2.右外連線right outer join 或者 right join
右外連線是在等值連線的基礎上加上被連線表的不匹配資料
select*
fromtesta
right outer jointestb
ontesta.a=testb.a
oracle支援的另一種寫法
select*
fromtesta,testb
wheretesta.a(+)=testb.a
結果: a
b ab
001
10a
001
10b
00330b
3.全外連線full outer join 或者 full join
全外連線是在等值連線的基礎上將左表和右表的未匹配資料都加上
select*
fromtesta
full outer jointestb
ontesta.a=testb.a
全外連線的等價寫法,對同一表先做左連線,然後右連線
selecttesta.*,testb.*
fromtesta
left outer jointestb
ontesta.a=testb.a
union
selecttesta.*,testb.*
fromtestb
left outer jointesta
ontesta.a=testb.a
結果: a
b a
b 001
10a
001
10b002
20a
00330b
內連線外連線
內連線 內連線也叫連線,是最早的一種連線,最早被稱為普通連線或自然連線。內連線是從結果中刪除其他被連線表中沒有匹配行的所有行,所以內連線可能會丟失資訊。內連線的語法 select fieldlist from table1 inner join table2 on table1.column tab...
SQL 內連線,外連線(左外連線 右外連線)
參考整理筆記 關鍵字 inner join on 語句 select from a table a inner join b table bon a.a id b.b id 執行結果 說明 組合兩個表中的記錄,返回關聯字段相符的記錄,也就是返回兩個表的交集 陰影 部分。關鍵字 left join o...
Oracle外連線,左外連線,右外連線,內連線簡析
內連線即普通等值連線 select e.ename,e.job,e.sal,d.dname from emp e inner join dept d on e.deptno d.deptno where e.sal 2000 select e.ename e.job,e.sal d.dname fr...