資料庫聯結學習

來源:互聯網
上載者:User
  聯結可分為以下幾類:

  • 內聯結(典型的聯結運算,使用像 = 或 <> 之類的比較子)。包括相等聯結和自然聯結。

    內聯結使用比較子根據每個表共有的列的值匹配兩個表中的行。例如,檢索 students courses 表中學生標識號相同的所有行。

     僅當至少有一個同屬於兩表的行符合聯結條件時,內聯結才返回行。內聯結消除與另一個表中的任何行不匹配的行。

  • 外聯結。外聯結可以是左向外聯結、右向外聯結或完整外部聯結。 外聯結會返回 FROM 子句中提到的至少一個表或視圖的所有行

    在 FROM 子句中指定外聯結時,可以由下列幾組關鍵字中的一組指定:

  • LEFT JOIN 或 LEFT OUTER JOIN。

    左向外聯結的結果集包括 LEFT OUTER 子句中指定的左表的所有行,而不僅僅是聯結列所匹配的行。如果左表的某行在右表中沒有匹配行,則在相關聯的結果集行中右表的所有挑選清單列均為空白值。

  • RIGHT JOIN 或 RIGHT OUTER JOIN。

    右向外聯結是左向外聯結的反向聯結。將返回右表的所有行。如果右表的某行在左表中沒有匹配行,則將為左表返回空值。

  • FULL JOIN 或 FULL OUTER JOIN。

    完整外部聯結返回左表和右表中的所有行。當某行在另一個表中沒有匹配行時,則另一個表的挑選清單列包含空值。如果表之間有匹配行,則整個結果集行包含基表的資料值。

  • 交叉聯結。

    交叉聯結返回左表中的所有行,左表中的每一行與右表中的所有行組合。交叉聯結也稱作笛卡爾積。結果集為 m*n

 

例子:

--建表table1,table2:
create table table1(id int,name varchar(10))
create table table2(id int,score int)
insert into table1 select 1,'lee'
insert into table1 select 2,'zhang'
insert into table1 select 4,'wang'
insert into table2 select 1,90
insert into table2 select 2,100
insert into table2 select 3,70

 

內聯:

select * from table1 join table2 on table1.id=table2.id
-------------結果-------------
id name id score
------------------------------
1 lee 1 90
2 zhang 2 100
------------------------------
注釋:只返回合格table1和table2的列 

 

左聯:

select * from table1 left join table2 on table1.id=table2.id
-------------結果-------------
id name id score
------------------------------
1 lee 1 90
2 zhang 2 100
4 wang NULL NULL
------------------------------
注釋:包含table1的所有子句,根據指定條件返回table2相應的欄位,不符合的以null顯示

 

右聯:

select * from table1 right join table2 on table1.id=table2.id
-------------結果-------------
id name id score
------------------------------
1 lee 1 90
2 zhang 2 100
NULL NULL 3 70
------------------------------
注釋:包含table2的所有子句,根據指定條件返回table1相應的欄位,不符合的以null顯示

 

完整外部聯結:

select * from table1 full join table2 on table1.id=table2.id
-------------結果-------------
id name id score
------------------------------
1 lee 1 90
2 zhang 2 100
4 wang NULL NULL
NULL NULL 3 70
------------------------------
注釋:返回左右串連的和(見上左、右串連)

 

 交叉聯結:

select * from table1 cross join table2
-------------結果-------------
id name id score
------------------------------
1 lee 1 90
2 zhang 1 90
4 wang 1 90
1 lee 2 100
2 zhang 2 100
4 wang 2 100
1 lee 3 70
2 zhang 3 70
4 wang 3 70
------------------------------
注釋:返回3*3=9條記錄,即笛卡爾積

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.