MySQL 不支持 FULL JOIN 关键字。但是,两个表上的 FULL JOIN 可以通过使用三个关键字来实现:LEFT JOINRIGHT JOINUNION 关键字。

示例:

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

表 1:Employee表

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

表2:Contact_Info表

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

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

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

UNION

SELECT Employee.Name, Employee.Age, Contact_Info.Address 
FROM Employee
RIGHT 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
LEFT JOIN Contact_Info
ON Employee.EmpID = Contact_Info.EmpID

UNION

SELECT Employee.*, Contact_Info.Address 
FROM Employee
RIGHT 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