六 SQL 表連線 全外部連線

2021-10-13 13:07:08 字數 1512 閱讀 2676

全外部連線並不是所有資料庫系統都支援,最常使用的mysql就不支援全外部連線。

全外部連線:是左外部連線和右外部連線的合集,因為即使在右表中不存在匹配連線條件的資料,左表中的所有記錄也將被放到結果集中,同樣即使在左表中不存在匹配連線條件的資料,右表中的所有記錄也將被放到結果集中。

如:使用全外部連線查詢每張訂單的資訊以及對應的客戶資訊

select o.fnumber,o.fprice,o.fcustomerid,c. from t_order o full outer join t_customer c on o.fcustomerid=c.fid
執行結果:

fnumber fprice fcustomerid fname fage

k001 100.00 1 tom 21

k002 200.00 1 tom 21

t003 300.00 1 tom 21

n002 100.00 2 mike 24

n003 500.00 3 jack 30

t001 300.00 4 tom 25

linda t002 100.00

可以看到前6條記錄都是符合連線條件的,而t_customer表中姓名為linda的客戶沒有對應的訂單,但是仍然被放到了結果集中,其無法匹配的字段填充的都是null,同樣訂單號為t002的訂單沒有匹配任何乙個客戶,但是仍然被放到了結果集中。

雖然在mysql中不支援全外部連線,不過由於全外部連線是左外部連線和右外部連線的合集,所以可以使用左外部連線和右外部連線來模擬實現全外部連線:使用左外部連線和右外部連線分別進行匹配查詢,然後使用union運算子來取兩個查詢結果集的合集。比如可以在mysql中執行下面的sql來實現t_order表和t_customer表的全外部連線:

select o.fnumber,o.fprice,o.fcustomerid,c.fname,

c.fage from t_order o left outer join t_customer c on o.fcustomerid=c.fid

union

select o.fnumber,o.fprice,o.fcustomerid,c.fname,

c.fage from t_order o right outer join t_customer c on o.fcustomerid=c.fid

執行結果:

fnumber fprice fcustomerid fname fage

k001 100.00 1 tom 21

k002 200.00 1 tom 21

t003 300.00 1 tom 21

n002 100.00 2 mike 24

t001 300.00 4 tom 25

n003 500.00 3 jack 30

linda t002 100.00

可以看到和全外部連線的執行結果是完全一致的

六 SQL 表連線 內連線

內連線組合兩張表,並且基於兩張表中的關聯關係來連線它們。使用內連線需要指定表中哪些字段組成關聯關係,並且需要指定基於什麼條件進行連線。內連線的語法如下 inner join table name on condition其中table name 為被關聯的表名,condition則為進行連線時的條件...

六 SQL 表連線 交叉連線

與內連線比起來,交叉連線非常簡單,因為它不存在on子句。交叉連線會將涉及到的所有表中的所有記錄都包含在結果集中。交叉連線,定義方式分為隱式連線和顯式連線。隱式連線 只要在select語句的from語句後將要進行交叉連線的表名列出即可,這種方式可以被幾乎任意資料庫系統支援。如 將t customer表...

六 SQL 表連線 簡介

表連線 進行多表檢索最常用的技術,使用join關鍵字將乙個或者多個表按照彼此間的關係連線為乙個結果集。資料準備 建立客戶表 mysql,mssqlserver,db2 create table t customer fid int not null fname varchar 20 not null...