SQL FULL JOIN
深入讲解 SQL FULL OUTER JOIN 全外连接保留两表并集与双向补 NULL 的规则、与其余三种 JOIN 的对比,以及在不支持原生 FULL OUTER JOIN 的 MySQL 中使用 UNION ALL 的等价写法。
学完这一章,你能够
- 深入讲解 SQL FULL OUTER JOIN 全外连接保留两表并集与双向补 NULL 的规则、与其余三种 JOIN 的对比,以及在不支持原生 FULL OUTER JOIN 的 MySQL 中使用 UNION ALL 的等价写法。
FULL OUTER JOIN 原理与语法
`FULL OUTER JOIN`(全外连接,常简称为 `FULL JOIN`)用于同时保留左右两张表的全部记录,无论对方表中是否存在匹配行。结果集既包含满足连接条件的交集部分,也包含只在左表或只在右表出现的非交集部分(缺失一侧的字段统一填 `NULL`),相当于合并了 `LEFT JOIN` 与 `RIGHT JOIN` 的效果。
标准语法为 `SELECT column_name(s) FROM table1 FULL OUTER JOIN table2 ON table1.column_name = table2.column_name;`:其中 `table1` 与 `table2` 为待连接的两张表,`ON` 子句声明连接键等值关系,`column_name(s)` 指定返回列。
全外连接具备三项鲜明特征:返回两表完整并集;单侧缺失项全部用 `NULL` 填充;在左右位置上完全对称,同时覆盖 `LEFT JOIN` 与 `RIGHT JOIN` 各自保留的记录。
学生与课程全外连接实例与四类 JOIN 总结
设有 `Students` 表(1-Alice、2-Bob、3-Charlie)和 `Courses` 表(101-1-Math、102-2-Science、103-4-History)。本地 SQLite 3.53.1 实测中,如果直接投影 `Students.StudentID`,右表独有的 History 行其 `Students.StudentID` 实际为 `NULL`(返回 `[None, None, 'History']`);若希望同时展示来自任意一侧的学号 `4`,应改写为 `COALESCE(Students.StudentID, Courses.StudentID) AS StudentID`,即可稳定得到 4 行并集:`[1, 'Alice', 'Math']`、`[2, 'Bob', 'Science']`、`[3, 'Charlie', None]` 与 `[4, None, 'History']`(1、2 为交集,3 仅在学生表故课程为 NULL,4 仅在课程表故姓名为 NULL)。
在同一组 `Students` 与 `Courses` 数据上横向实测四种核心连接,`INNER JOIN` 返回 2 行、`LEFT JOIN` 返回 3 行、`RIGHT JOIN` 返回 3 行、`FULL OUTER JOIN` 返回 4 行,直观体现了交集、单侧外连接与双向全外连接的集合层级关系。
站点访问全外连接与 MySQL 兼容性替代方案
在示例数据库 `Websites`(6 行)与 `access_log`(9 行)中,同样可以通过 `Websites.id = access_log.site_id` 执行全外连接,确保既有无访问的站点、也有无站点归属的日志时都不会漏掉任何一侧的数据。
需要特别注意数据库方言支持差异:PostgreSQL、SQL Server、Oracle 以及 SQLite 3.39+ 均原生支持 `FULL OUTER JOIN`,而 MySQL 至今不支持原生 `FULL OUTER JOIN` 语法。在本地 SQLite 3.53.1 中直接运行 `Websites FULL OUTER JOIN access_log ORDER BY access_log.count DESC` 返回 10 行(含无日志的 `['stackoverflow', None, None]`);此外,在同时存在孤立站点(id=7)和孤立日志(site_id=6)的 11 行场景中,实测验证了 MySQL 通用替代写法——`LEFT JOIN` 结合 `UNION ALL` 再拼接右连接中 `WHERE Websites.id IS NULL` 的未匹配行——与原生 `FULL OUTER JOIN` 结果逐行一致。
示例表:Students
| StudentID | Name |
| 1 | Alice |
| 2 | Bob |
| 3 | Charlie |
示例表:Courses
| CourseID | StudentID | CourseName |
| 101 | 1 | Math |
| 102 | 2 | Science |
| 103 | 4 | History |
Students FULL OUTER JOIN Courses 查询结果(COALESCE 合并连接键)
| StudentID | Name | CourseName |
| 1 | Alice | Math |
| 2 | Bob | Science |
| 3 | Charlie | NULL |
| 4 | NULL | History |
四种常用 SQL JOIN 对比总结
| JOIN 类型 | 返回内容 |
| INNER JOIN | 两表满足连接条件的交集记录(示例返回 2 行)。 |
| LEFT JOIN | 左表全部记录及匹配的右表记录(示例返回 3 行)。 |
| RIGHT JOIN | 右表全部记录及匹配的左表记录(示例返回 3 行)。 |
| FULL OUTER JOIN | 两表完整并集,含所有匹配及单侧未匹配记录(示例返回 4 行)。 |
在本地 SQLite 3.53.1 验证 FULL OUTER JOIN、COALESCE 键合并与 MySQL UNION ALL 等价替代
展开查看收起
"""Offline SQLite lab for SQL Chapter 22: FULL OUTER JOIN."""
import json
import sqlite3
import sys
def make_case(name: str, summary: str, expected, actual) -> dict:
return {
"name": name,
"summary": summary,
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main() -> None:
conn = sqlite3.connect(":memory:")
cur = conn.cursor()
cur.executescript(
"""
CREATE TABLE Students (
StudentID INT,
Name TEXT
);
INSERT INTO Students VALUES
(1, 'Alice'),
(2, 'Bob'),
(3, 'Charlie');
CREATE TABLE Courses (
CourseID INT,
StudentID INT,
CourseName TEXT
);
INSERT INTO Courses VALUES
(101, 1, 'Math'),
(102, 2, 'Science'),
(103, 4, 'History');
"""
)
direct_full = [
list(r)
for r in cur.execute(
"""
SELECT Students.StudentID, Students.Name, Courses.CourseName
FROM Students
FULL OUTER JOIN Courses
ON Students.StudentID = Courses.StudentID
ORDER BY COALESCE(Students.StudentID, Courses.StudentID)
"""
).fetchall()
]
coalesced_full = [
list(r)
for r in cur.execute(
"""
SELECT COALESCE(Students.StudentID, Courses.StudentID) AS StudentID,
Students.Name,
Courses.CourseName
FROM Students
FULL OUTER JOIN Courses
ON Students.StudentID = Courses.StudentID
ORDER BY StudentID
"""
).fetchall()
]
case1 = make_case(
"students_courses_full_outer_join",
"Verify FULL OUTER JOIN returns union of Students and Courses, showing direct left-key NULL vs COALESCE",
{
"direct": [
[1, "Alice", "Math"],
[2, "Bob", "Science"],
[3, "Charlie", None],
[None, None, "History"],
],
"coalesced": [
[1, "Alice", "Math"],
[2, "Bob", "Science"],
[3, "Charlie", None],
[4, None, "History"],
],
},
{
"direct": direct_full,
"coalesced": coalesced_full,
},
)
counts = {
"inner": cur.execute(
"SELECT COUNT(*) FROM Students INNER JOIN Courses ON Students.StudentID = Courses.StudentID"
).fetchone()[0],
"left": cur.execute(
"SELECT COUNT(*) FROM Students LEFT JOIN Courses ON Students.StudentID = Courses.StudentID"
).fetchone()[0],
"right": cur.execute(
"SELECT COUNT(*) FROM Students RIGHT JOIN Courses ON Students.StudentID = Courses.StudentID"
).fetchone()[0],
"full": cur.execute(
"SELECT COUNT(*) FROM Students FULL OUTER JOIN Courses ON Students.StudentID = Courses.StudentID"
).fetchone()[0],
}
case2 = make_case(
"join_family_comparison",
"Compare row counts across INNER, LEFT, RIGHT, and FULL OUTER JOIN on Students and Courses",
{"inner": 2, "left": 3, "right": 3, "full": 4},
counts,
)
cur.executescript(
"""
CREATE TABLE Websites (
id INT,
name TEXT,
url TEXT,
alexa INT,
country TEXT
);
INSERT INTO Websites VALUES
(1, 'Google', 'https://www.google.com/', 1, 'USA'),
(2, '淘宝', 'https://www.taobao.com/', 13, 'CN'),
(3, '蓝色天空', 'https://www.mbsky.com/', 4689, 'CN'),
(4, '微博', 'https://weibo.com/', 20, 'CN'),
(5, 'Facebook', 'https://www.facebook.com/', 3, 'USA'),
(7, 'stackoverflow', 'https://stackoverflow.com/', 0, 'IND');
CREATE TABLE access_log (
aid INT,
site_id INT,
count INT,
date TEXT
);
INSERT INTO access_log VALUES
(1, 1, 45, '2016-05-10'),
(2, 3, 100, '2016-05-13'),
(3, 1, 230, '2016-05-14'),
(4, 2, 10, '2016-05-14'),
(5, 5, 205, '2016-05-14'),
(6, 4, 13, '2016-05-15'),
(7, 3, 220, '2016-05-15'),
(8, 5, 545, '2016-05-16'),
(9, 3, 201, '2016-05-17');
"""
)
site_full = [
list(r)
for r in cur.execute(
"""
SELECT Websites.name, access_log.count, access_log.date
FROM Websites
FULL OUTER JOIN access_log
ON Websites.id = access_log.site_id
ORDER BY access_log.count DESC, Websites.id ASC
"""
).fetchall()
]
case3 = make_case(
"websites_access_log_full_join",
"Verify Websites FULL OUTER JOIN access_log returns 10 rows including unmatched stackoverflow",
{
"row_count": 10,
"first_row": ["Facebook", 545, "2016-05-16"],
"last_row": ["stackoverflow", None, None],
},
{
"row_count": len(site_full),
"first_row": site_full[0],
"last_row": site_full[-1],
},
)
# Also test MySQL emulation pattern (LEFT JOIN UNION ALL unmatched RIGHT JOIN) with unmatched rows on both sides
cur.execute("INSERT INTO access_log VALUES (10, 6, 111, '2016-03-09')")
native_both = [
list(r)
for r in cur.execute(
"""
SELECT Websites.name, access_log.count, access_log.date
FROM Websites
FULL OUTER JOIN access_log ON Websites.id = access_log.site_id
ORDER BY access_log.count DESC, Websites.name ASC
"""
).fetchall()
]
emulated_both = [
list(r)
for r in cur.execute(
"""
SELECT name, count, date FROM (
SELECT Websites.name AS name, access_log.count AS count, access_log.date AS date
FROM Websites
LEFT JOIN access_log ON Websites.id = access_log.site_id
UNION ALL
SELECT Websites.name AS name, access_log.count AS count, access_log.date AS date
FROM Websites
RIGHT JOIN access_log ON Websites.id = access_log.site_id
WHERE Websites.id IS NULL
)
ORDER BY count DESC, name ASC
"""
).fetchall()
]
case4 = make_case(
"mysql_union_emulation_equivalence",
"Verify LEFT JOIN + UNION ALL unmatched RIGHT JOIN matches native FULL OUTER JOIN with unmatched rows on both sides",
{
"row_count": 11,
"matches_native": True,
"has_null_name": True,
"has_null_count": True,
},
{
"row_count": len(native_both),
"matches_native": native_both == emulated_both,
"has_null_name": any(r[0] is None and r[1] == 111 for r in native_both),
"has_null_count": any(r[0] == "stackoverflow" and r[1] is None for r in native_both),
},
)
conn.close()
payload = {
"version": f"CPython {sys.version.split()[0]} / SQLite {sqlite3.sqlite_version}",
"cases": [case1, case2, case3, case4],
}
print(json.dumps(payload, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
先执行 `A LEFT JOIN B`,再用 `UNION ALL` 拼接 `A RIGHT JOIN B ... WHERE A.key IS NULL`(仅取右表独有未匹配行),即可完整且不重复地模拟 FULL OUTER JOIN。