解析:內聯,左外聯,右外聯,全鏈接,交叉鏈接的區別

鏈接分爲:內鏈接、外鏈接、交叉鏈接 
1、內鏈接——最經常使用 
定義:
僅將兩個表中知足鏈接條件的行組合起來做爲結果集。 
在內鏈接中,只有在兩個表中匹配的行才能在結果集中出現 
關鍵詞:INNER JOIN 
格式:SELECT 列名錶 FROM 表名1 [INNER] JOIN 表名2 ON或WHERE 條件表達式 
說明: 
(1)列名錶中的列名能夠出自後面的兩個表,但若是兩個表中有同名列,應在列名前標明出處,格式爲:表名.列名 
(2)若鏈接的兩個表名字太長,能夠爲它們起個別名。 格式爲:表名 AS 別名 
(3)INNER是默認方式,能夠省略
eg:
select *
from   t_institution i
inner join t_teller t
on i.inst_no = t.inst_no
where i.inst_no = "5801"
其中inner能夠省略。
等價於早期的鏈接語法
select *
from t_institution i, t_teller t
where i.inst_no = t.inst_no
and i.inst_no = "5801"數據庫

2、外鏈接 
一、左(外)鏈接 
定義:在內鏈接的基礎上,還包含左表中全部不符合條件的數據行,並在其中的右表列填寫NULL 
關鍵字:LEFT JOIN
eg:
select *
from   t_institution i
left outer join t_teller t
on i.inst_no = t.inst_no
其中outer能夠省略。
注意: 
當在內鏈接查詢中加入條件是,不管是將它加入到join子句,仍是加入到where子句,其效果是徹底同樣的,但對於外鏈接狀況就不一樣了。當把條件加入到 join子句時,SQL Server、Informix會返回外鏈接表的所有行,而後使用指定的條件返回第二個表的行。若是將條件放到where子句 中,SQL Server將會首先進行鏈接操做,而後使用where子句對鏈接後的行進行篩選。下面的兩個查詢展現了條件放置位子對執行結果的影響:
條件在join子句
select *
from   t_institution i
left outer join t_teller t
on i.inst_no = t.inst_no
and i.inst_no = 「5801」

結果是:
inst_no     inst_name             inst_no     teller_no   teller_name
5801        天河區                5801        0001        tom
5801        天河區                5801        0002        david
5802        越秀區
5803        白雲區

條件在where子句
select *
from   t_institution i
left outer join t_teller t
on i.inst_no = t.inst_no
where i.inst_no = 「5801」

結果是:
inst_no     inst_name             inst_no     teller_no   teller_name
5801           天河區                    5801          0001               tom
5801           天河區                    5801          0002              david

二、右(外)鏈接 
定義:
在內鏈接的基礎上,還包含右表中全部不符合條件的數據行,並在其中的左表列填寫NULL 
關鍵字:RIGHT JOIN 
三、徹底鏈接 
定義:
在內鏈接的基礎上,還包含兩個表中全部不符合條件的數據行,並在其中的左表、和右表列填寫NULL 
關鍵字:FULL JOINorm

3、交叉鏈接 
定義:
將兩個表的全部行進行組合,鏈接後的行數爲兩個表的乘積數。(笛卡爾積) 
關鍵詞:CROSS JOIN 
格式:FROM 表名1 CROSS JOIN 表名2遞歸

四, 自身鏈接
自身鏈接是指同一個表本身與本身進行鏈接。這種一元鏈接一般用於從自反關係(也稱做遞歸關係)中抽取數據。例如人力資源數據庫中僱員與老闆的關係。
下面例子是在機構表中查找本機構和上級機構的信息。
select s.inst_no superior_inst, s.inst_name sup_inst_name, i.inst_no, i.inst_name
from t_institution i
join t_institution s
on i.superior_inst = s.inst_no

結果是:
superior_inst sup_inst_name         inst_no     inst_name
800                             廣州市                5801        天河區
800                             廣州市                5802        越秀區
800                             廣州市                5803        白雲區資源

相關文章
相關標籤/搜索