SQL Server (Transact-SQL) FULL JOIN 关键字(或有时称为 FULL OUTER JOIN)用于根据列之间的匹配来组合两个表的列值,并返回两个表的所有行。如果任何表中都没有匹配项,则结果表将包含 NULL 值。

SQL Server 全连接

语法

给出了在 SQL Server (Transact-SQL) 中使用 FULL JOIN 关键字的语法下面:

SELECT table1.column1, table1.column2, table2.column1, table2.column2, ...
FROM table1
FULL JOIN table2
ON table1.matching_column = table2.matching_column; 

示例:

考虑名为 Employee 和 Contact_Info 的数据库表,其中包含以下记录:

表 1:Employee表

EmpIDNameCityAgeSalary
1JohnLondon253000
2MarryNew York242750
3JoParis272800
4KimAmsterdam303100
5RameshNew Delhi283000
6HuangBeijing282800

表 2:Contact_Info table

Phone_NumberEmpIDAddressGender
+1-80540980002Brooklyn, New York, USAF
+33-1479961013Grenelle, Paris, FranceM
+31-2011503194Geuzenveld, Amsterdam, NetherlandsF
+86-10997324586Yizhuangzhen, Beijing, ChinaM
+65-672348247Yishun, SingaporeM
+81-3577990728Koto City, Tokyo, JapanM

根据匹配列EmpID完全连接 Employee 和 Contact_Info 表,查询如下。这将从 Employee 表中获取 Name 和 Age 列,并从 Contact_Info 中获取 Address 列

SELECT Employee.Name, Employee.Age, Contact_Info.Address 
FROM Employee
FULL JOIN Contact_Info
ON Employee.EmpID = Contact_Info.EmpID; 

这将产生如下所示的结果:

NameAgeAddress
John25
Marry24Brooklyn, New York, USA
Jo27Grenelle, Paris, France
Kim30Geuzenveld, Amsterdam, Netherlands
Ramesh28
Huang28Yizhuangzhen, Beijing, China
Yishun, Singapore
Koto City, Tokyo, Japan

要获取表的所有字段,使用 table.* 关键字,例如 - 要获取 Employee 表的所有字段,Employee.* 用于以下查询:

SELECT Employee.*, Contact_Info.Address 
FROM Employee
FULL JOIN Contact_Info
ON Employee.EmpID = Contact_Info.EmpID; 

以下代码的结果将是:

EmpIDNameCityAgeSalaryAddress
1JohnLondon253000
2MarryNew York242750Brooklyn, New York, USA
3JoParis272800Grenelle, Paris, France
4KimAmsterdam303100Geuzenveld, Amsterdam, Netherlands
5RameshNew Delhi283000
6HuangChina282800Yizhuangzhen, Beijing, China
Yishun, Singapore
Koto City, Tokyo, Japan