SQL RIGHT JOIN
解析 SQL RIGHT JOIN / RIGHT OUTER JOIN 右外连接保留右表全部记录并向未匹配左表列补 NULL 的行为,对比与 LEFT JOIN 的对称等价性,并在 SQLite 3.53.1 实测验证。
学完这一章,你能够
- 解析 SQL RIGHT JOIN / RIGHT OUTER JOIN 右外连接保留右表全部记录并向未匹配左表列补 NULL 的行为,对比与 LEFT JOIN 的对称等价性,并在 SQLite 3.53.1 实测验证。
RIGHT JOIN 核心概念与语法
`RIGHT JOIN`(右外连接)与 `LEFT JOIN` 互为镜像:它以连接语句右侧的表为基准,返回右表中的全部行;即便左表中找不到对应匹配项,右表记录仍会被保留,对应的左表字段则以 `NULL` 填充。
标准语法写作 `SELECT column_name(s) FROM table1 RIGHT JOIN table2 ON table1.column_name = table2.column_name;`,完整形式为 `RIGHT OUTER JOIN`(两者等价)。这里 `table1` 为左表,`table2` 是结果中全量保留的右表,`ON` 指定两表匹配字段。
`RIGHT JOIN` 的两个核心特征是:无条件保留右表全部记录;当左表没有对应匹配行时,以 `NULL` 填充结果集中的左表各列。
员工与部门右外连接及与 LEFT JOIN 的对称关系
以 `Employees` 表(1-Alice-10、2-Bob-20、3-Charlie-NULL)和 `Departments` 表(10-HR、20-IT、30-Finance)为例,执行 `SELECT Employees.Name, Departments.DepartmentName FROM Employees RIGHT JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID;`。本地 SQLite 3.53.1 实测确认 `RIGHT JOIN` 与 `RIGHT OUTER JOIN` 均返回 3 行:`['Alice', 'HR']`、`['Bob', 'IT']` 以及左表无匹配的 `[None, 'Finance']`,而未分配部门的 Charlie 不在结果中。
对比 `LEFT JOIN` 与 `RIGHT JOIN` 的差异:`LEFT JOIN` 保留左表全部行,`RIGHT JOIN` 保留右表全部行。在 SQL 工程实践中,调换左右表位置后 `Departments LEFT JOIN Employees` 与 `Employees RIGHT JOIN Departments` 完全等价(本地 SQLite 3.53.1 已实测一致),而同顺序下 `Employees LEFT JOIN Departments` 会保留 Charlie 并舍弃 Finance。
站点与访问日志右外连接实测
为了直观展示右表独有行的保留效果,先向 `access_log` 表追加一条在 `Websites` 中不存在对应站点的记录:`INSERT INTO access_log (aid, site_id, count, date) VALUES (10, 6, 111, '2016-03-09');`(此时 `access_log` 共 10 行,其中 `site_id = 6` 在 `Websites` 无对应项;注意原日志示例文本中曾将日期误标为 2016-03-19 且总行数仍写 9 rows,实际插入后应为 10 行、日期为 `2016-03-09`)。
以 `Websites` 为左表、`access_log` 为右表执行 `SELECT Websites.name, access_log.count, access_log.date FROM Websites RIGHT JOIN access_log ON access_log.site_id = Websites.id ORDER BY access_log.count DESC;`。本地 SQLite 3.53.1 实测返回全部 10 条访问记录:首行为 `['Facebook', 545, '2016-05-16']`,未匹配站点的 `site_id = 6` 行被保留为 `[None, 111, '2016-03-09']`,而无访问记录的 `stackoverflow`(id=7)不会出现在右连接结果中。
示例表:Employees
| EmployeeID | Name | DepartmentID |
|---|---|---|
| 1 | Alice | 10 |
| 2 | Bob | 20 |
| 3 | Charlie | NULL |
示例表:Departments
| DepartmentID | DepartmentName |
|---|---|
| 10 | HR |
| 20 | IT |
| 30 | Finance |
Employees RIGHT JOIN Departments 查询结果
| Name | DepartmentName |
|---|---|
| Alice | HR |
| Bob | IT |
| NULL | Finance |
在本地 SQLite 3.53.1 验证 RIGHT JOIN、与 LEFT JOIN 对称等价性及访问日志右连接
"""Offline SQLite lab for SQL Chapter 21: RIGHT 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 Employees (
EmployeeID INT,
Name TEXT,
DepartmentID INT
);
INSERT INTO Employees VALUES
(1, 'Alice', 10),
(2, 'Bob', 20),
(3, 'Charlie', NULL);
CREATE TABLE Departments (
DepartmentID INT,
DepartmentName TEXT
);
INSERT INTO Departments VALUES
(10, 'HR'),
(20, 'IT'),
(30, 'Finance');
"""
)
right_res = [
list(r)
for r in cur.execute(
"""
SELECT Employees.Name, Departments.DepartmentName
FROM Employees
RIGHT JOIN Departments
ON Employees.DepartmentID = Departments.DepartmentID
ORDER BY Departments.DepartmentID
"""
).fetchall()
]
right_outer_res = [
list(r)
for r in cur.execute(
"""
SELECT Employees.Name, Departments.DepartmentName
FROM Employees
RIGHT OUTER JOIN Departments
ON Employees.DepartmentID = Departments.DepartmentID
ORDER BY Departments.DepartmentID
"""
).fetchall()
]
case1 = make_case(
"right_join_vs_right_outer_join",
"Verify RIGHT JOIN and RIGHT OUTER JOIN preserve all Departments including Finance with NULL Name",
{
"rows": [["Alice", "HR"], ["Bob", "IT"], [None, "Finance"]],
"same_as_right_outer": True,
},
{
"rows": right_res,
"same_as_right_outer": right_res == right_outer_res,
},
)
swapped_left = [
list(r)
for r in cur.execute(
"""
SELECT Employees.Name, Departments.DepartmentName
FROM Departments
LEFT JOIN Employees
ON Employees.DepartmentID = Departments.DepartmentID
ORDER BY Departments.DepartmentID
"""
).fetchall()
]
emp_left = [
list(r)
for r in cur.execute(
"""
SELECT Employees.Name, Departments.DepartmentName
FROM Employees
LEFT JOIN Departments
ON Employees.DepartmentID = Departments.DepartmentID
ORDER BY Employees.EmployeeID
"""
).fetchall()
]
case2 = make_case(
"right_join_vs_left_join_symmetry",
"Verify Departments LEFT JOIN Employees equals Employees RIGHT JOIN Departments, contrasting with Employees LEFT JOIN Departments",
{
"swapped_left_equals_right": True,
"employees_left_rows": [["Alice", "HR"], ["Bob", "IT"], ["Charlie", None]],
},
{
"swapped_left_equals_right": swapped_left == right_res,
"employees_left_rows": emp_left,
},
)
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');
INSERT INTO access_log (aid, site_id, count, date)
VALUES (10, 6, 111, '2016-03-09');
"""
)
site_right = [
list(r)
for r in cur.execute(
"""
SELECT Websites.name, access_log.count, access_log.date
FROM Websites
RIGHT JOIN access_log
ON access_log.site_id = Websites.id
ORDER BY access_log.count DESC
"""
).fetchall()
]
unmatched_log_rows = [r for r in site_right if r[0] is None]
case3 = make_case(
"websites_right_join_access_log",
"Verify Websites RIGHT JOIN access_log keeps unmatched site_id=6 row with NULL name and excludes stackoverflow",
{
"row_count": 10,
"top_row": ["Facebook", 545, "2016-05-16"],
"unmatched_rows": [[None, 111, "2016-03-09"]],
"has_stackoverflow": False,
},
{
"row_count": len(site_right),
"top_row": site_right[0],
"unmatched_rows": unmatched_log_rows,
"has_stackoverflow": any(r[0] == "stackoverflow" for r in site_right),
},
)
conn.close()
payload = {
"version": f"CPython {sys.version.split()[0]} / SQLite {sqlite3.sqlite_version}",
"cases": [case1, case2, case3],
}
print(json.dumps(payload, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 确认 RIGHT JOIN 与 RIGHT OUTER JOIN 均返回含 [None, 'Finance'] 的 3 行,验证交换表序的 LEFT JOIN 与 RIGHT JOIN 完全等价,并确认 Websites RIGHT JOIN access_log 保留 site_id=6 的孤立日志行。
所需环境:Windows x64、CPython 3.12.14、内置 sqlite3(SQLite 3.53.1)本地离线环境。
当前源码 SHA256:335841849f206624b34392db327f277855c91665427dc0dc004ee5a88cd8b609
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、内置 sqlite3(SQLite 3.53.1)本地离线环境。
ZIP SHA256:79c15a4bd498b7cadf17074c84da024a49da5949ca304f89a5bbb6f5b0f3cb75
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
怎样把 `SELECT a.x, b.y FROM A RIGHT JOIN B ON a.id = b.aid;` 改写成等价的 LEFT JOIN 语句?
展开参考解答
将左右两表顺序互换即可:`SELECT a.x, b.y FROM B LEFT JOIN A ON a.id = b.aid;`。