Oracle 內連線(inner join)、外連線(outer join)、全連線(full join)
http://blog.itpub.net/30175262/viewspace-1472290/
之前沒有用過 full outer join,第一次用,學習一下
Student表
Color表
Oracle中的連線可分為,內連線(inner join)、外連線(outer join)、全連線(full join),不光是Oracle,其他很多的資料庫也都有這3種連線查詢方式:
內連線inner join/join
也叫自連線,這是我們經常用到的查詢方式,內連線查詢只能查詢出匹配的記錄,匹配不上的記錄時無法查詢出來的 ,以下三種查詢結果一樣
select * from student s, color c where s.stuname = c.stuname;
select * from student s inner join color c on s.stuname = c.stuname;
select * from student s join color c on s.stuname = c.stuname;
外連線outer join
可進一步分為左外連線left outer join和右外連線right outer join,(簡稱左連線left join,右連線 right join)。
左外連線
左連線就是以左邊的表(left join 左邊的表)為主表,即使有些記錄關聯不上,主表的資訊也能全部查詢出來,也就是左邊的表資料全部展示,右邊表的資料複合條件的展示,不符合條件的以空值代替,適合那種需要求出維度(比如求出所有人員)的需求:
select * from student s left join color c on s.stuname = c.stuname;
等同於select * from student s left outer join color c on s.stuname = c.stuname;
右外連線
如果有需求要求在結果中展現所有的顏色資訊,就可以用右連線:
還有另一種寫法,可以達到相同的外連線效果:比如左外連線等同於以下的語句:
select * from student s ,color c where s.stuname = c.stuname(+);
同樣右連線是這樣的:
select * from student s ,color c where s.stuname(+) = c.stuname;
在(+)計算時,哪個帶(+)哪個需要條件符合的,另一個全部的。即放左即右連線,放右即左連線。
全連線full join/full outer join
語法是語法為full join ... on ...,全連線的查詢結果是左外連線和右外連線查詢結果的並集,即使一些記錄關聯不上,也能夠把部分資訊查詢出來:
產生M+N的結果集,列出兩表全部的,不符合條件的,以空值代替。
select * from student s full join color c on s.stuname = c.stuname;
select * from student s full join color c on 1=1
笛卡爾乘積cross join
即不加任何條件,達到 M*N 的結果集。
以下兩種查詢結果一樣。
select * from student s cross join color c
select * from student s , color c
注意:如果cross join加上where on s.stuname = c.stuname條件,會產生跟自連線一樣的結果(cross join 後加上 on 報錯):
加上條件,產生跟自連線一樣的結果。
select * from student s cross join color c where s.stuname = c.stuname;
自連線結果集的cross join連線結果
總結
ü 所有的join連線,都可以加上類似where a.id='1000'的條件,達到同樣的效果。因為on不能做這種判斷,只能是
ü 除了cross join不可以加on外,其它join連線都必須加上on關鍵字,後都可加where條件。
ü 雖然都可以加where條件,但是他們只在標準連線的結果集上查詢where條件。比如左外連線的結果沒有class的三班,所以如果加 where class.id='C003'雖然在表中有,但在左連線結果集中沒有,所以查詢後,是沒有記錄的。
A表有100條資料,B表有80條資料,left join on 1=1,where 1=1的結果是:
應該是笛卡爾積
A表有100條資料,B表有80條資料,left join on 1=2,where 1=1的結果是:
應該是A表的值
測試:
select * from student s left join color c on 1=1 where 1=1
select * from student s left join color c on 1=2 where 1=1