SQL Server (Transact-SQL) FULL OUTER JOIN 关键字(或有时称为 FULL JOIN) 用于根据列之间的匹配来组合两个表的列值,并返回两个表的所有行。如果任何表中都没有匹配项,则结果表将包含 NULL 值。
语法
在 SQL Server (Transact-SQL) 中使用 FULL OUTER JOIN 关键字的语法如下:
SELECT table1.column1, table1.column2, table2.column1, table2.column2, ...
FROM table1
FULL OUTER JOIN table2
ON table1.matching_column = table2.matching_column;
示例:
考虑一个数据库,其中包含名为 Employee 和 Contact_Info 的表,其中包含以下记录:
表 1:Employee 表
EmpID | Name | City | Age | Salary |
---|---|---|---|---|
1 | John | London | 25 | 3000 |
2 | Marry | New York | 24 | 2750 |
3 | Jo | Paris | 27 | 2800 |
4 | Kim | Amsterdam | 30 | 3100 |
5 | Ramesh | New Delhi | 28 | 3000 |
6 | Huang | Beijing | 28 | 2800 |
表2:Contact_Info表
Phone_Number | EmpID | Address | Gender |
---|---|---|---|
+1-8054098000 | 2 | Brooklyn, New York, USA | F |
+33-147996101 | 3 | Grenelle, Paris, France | M |
+31-201150319 | 4 | Geuzenveld, Amsterdam, Netherlands | F |
+86-1099732458 | 6 | Yizhuangzhen, Beijing, China | M |
+65-67234824 | 7 | Yishun, Singapore | M |
+81-357799072 | 8 | Koto City, Tokyo, Japan | M |
要基于匹配列 EmpID 完全外部联接 Employee 和 Contact_Info 表,下面给出查询。这将从 Employee 表中获取 Name 和 Age 列,并从 Contact_Info 中获取 Address 列
SELECT Employee.Name, Employee.Age, Contact_Info.Address
FROM Employee
FULL OUTER JOIN Contact_Info
ON Employee.EmpID = Contact_Info.EmpID;
这将产生如下所示的结果:
Name | Age | Address |
---|---|---|
John | 25 | |
Marry | 24 | Brooklyn, New York, USA |
Jo | 27 | Grenelle, Paris, France |
Kim | 30 | Geuzenveld, Amsterdam, Netherlands |
Ramesh | 28 | |
Huang | 28 | Yizhuangzhen, Beijing, China |
Yishun, Singapore | ||
Koto City, Tokyo, Japan |
要获取表的所有字段,使用 table.* 关键字,例如 - 要获取 Employee 表的所有字段,Employee.* 用于以下查询:
SELECT Employee.*, Contact_Info.Address
FROM Employee
FULL OUTER JOIN Contact_Info
ON Employee.EmpID = Contact_Info.EmpID;
以下代码的结果将是:
EmpID | Name | City | Age | Salary | Address |
---|---|---|---|---|---|
1 | John | London | 25 | 3000 | |
2 | Marry | New York | 24 | 2750 | Brooklyn, New York, USA |
3 | Jo | Paris | 27 | 2800 | Grenelle, Paris, France |
4 | Kim | Amsterdam | 30 | 3100 | Geuzenveld, Amsterdam, Netherlands |
5 | Ramesh | New Delhi | 28 | 3000 | |
6 | Huang | China | 28 | 2800 | Yizhuangzhen, Beijing, China |
Yishun, Singapore | |||||
Koto City, Tokyo, Japan |