SQL 连接(JOIN)
系统梳理 SQL 多表连接(JOIN)的核心概念、七种连接类型的集合语义差异与 Customers/Orders、Websites/access_log 关联示例,并在本地 SQLite 3.53.1 完整实测验证。
学完这一章,你能够
- 系统梳理 SQL 多表连接(JOIN)的核心概念、七种连接类型的集合语义差异与 Customers/Orders、Websites/access_log 关联示例,并在本地 SQLite 3.53.1 完整实测验证。
多表连接核心概念与七种 JOIN 类型
在关系型数据库中,业务数据通常按实体拆分存放在不同数据表中。SQL `JOIN` 子句用于依据表之间的关联字段把两张或多张表的行横向拼接起来,常见集合形态包括内连接、左外连接、右外连接、全外连接以及排他连接等七种组合关系。
以 `Customers`(含 Alice、Bob、Charlie 三位客户,CustomerID 为 1、2、3)和 `Orders`(含 101/1/Laptop、102/2/Phone、103/4/Tablet 三笔订单)两张示例表作横向对照:在本地 SQLite 3.53.1 实测中,`INNER JOIN` 仅返回双方都匹配的 2 行(CustomerID 1 与 2);`LEFT JOIN` 保留全部 3 位客户,Charlie 的 `Product` 填充为 `NULL`;`RIGHT JOIN` 保留全部 3 笔订单,OrderID 103 的 `Name` 填充为 `NULL`;`FULL OUTER JOIN` 返回双方并集共 4 行;`CROSS JOIN` 产生 3×3=9 行笛卡尔积;`NATURAL JOIN` 按同名列 `CustomerID` 自动等值匹配返回 2 行;而在 `Staff` 自连接(`SELF JOIN`)中,同一张表赋予别名 `e` 与 `m` 后即可关联出员工与上级主管层级关系。
SQL JOIN 标准语法与参数含义
`JOIN` 通过两张表的共同键把分散在不同表中的字段合并到同一结果集中。最常用的连接方式是 `INNER JOIN`(直接写 `JOIN` 时与之完全等价),它只返回满足 `ON` 连接条件的交集行。
基本语法写作 `SELECT column1, column2, ... FROM table1 JOIN table2 ON condition;`:其中 `column1, column2, ...` 为需要返回的列名列表(省略具体列名而写 `*` 时返回所有列),`table1` 与 `table2` 分别为参与连接的左表与右表,`condition` 为连接匹配条件(通常是两表对应键的等值比较)。本地 SQLite 3.53.1 实测确认 `JOIN ... ON` 与 `INNER JOIN ... ON` 返回完全一致的结果集。
站点与访问日志关联实测及主要连接速览
在示例数据库场景中,`Websites` 表记录了 6 条站点主数据(id 分别为 1、2、3、4、5、7),`access_log` 表记录了 9 条访问统计明细(aid 1 至 9,覆盖 site_id 1 至 5)。两张表通过 `Websites.id = access_log.site_id` 建立一对多关联关系,其中 id 为 7 的站点在访问日志中尚无对应记录。
执行 `SELECT Websites.id, Websites.name, access_log.count, access_log.date FROM Websites INNER JOIN access_log ON Websites.id = access_log.site_id;` 后,SQLite 3.53.1 实测返回全部 9 条匹配记录(首条为 `[1, 'Google', 45, '2016-05-10']`,末条为 `[3, '蓝色天空', 201, '2016-05-17']`),未产生访问记录的 id=7 站点被自动排除。
后续章节将依次深入剖析四种最核心的 SQL 连接类型:`INNER JOIN`(两表均存在匹配时返回交集行)、`LEFT JOIN`(保留左表全部行,右表无匹配填 NULL)、`RIGHT JOIN`(保留右表全部行,左表无匹配填 NULL)以及 `FULL JOIN` / `FULL OUTER JOIN`(保留左右两表全部行并补齐缺失侧 NULL)。
SQL 常见七种 JOIN 连接类型总览
| 类型 | 描述 |
| INNER JOIN | 仅返回两个表中满足连接条件的匹配记录(交集)。 |
| LEFT JOIN | 保留左表全部记录;右表无匹配时以 NULL 补齐右表列。 |
| RIGHT JOIN | 保留右表全部记录;左表无匹配时以 NULL 补齐左表列。 |
| FULL OUTER JOIN | 返回左右两表的完整并集,包含匹配行及各自未匹配行(缺失侧填 NULL)。 |
| CROSS JOIN | 返回两表行的笛卡尔积组合(m×n 行),不需要 ON 条件。 |
| SELF JOIN | 将表通过不同别名与自身连接,常用于组织架构或层级查询。 |
| NATURAL JOIN | 自动按两张表中所有同名列进行等值连接(生产环境建议显式写 ON 以免表结构变更引发隐式匹配)。 |
示例表 1:Customers
| CustomerID | Name |
| 1 | Alice |
| 2 | Bob |
| 3 | Charlie |
示例表 2:Orders
| OrderID | CustomerID | Product |
| 101 | 1 | Laptop |
| 102 | 2 | Phone |
| 103 | 4 | Tablet |
Customers 与 Orders 各连接类型结果对照
| JOIN 类型 | 结果 |
| INNER JOIN | 仅返回两表 CustomerID 匹配的 2 行:Alice-Laptop(1)与 Bob-Phone(2)。 |
| LEFT JOIN | 返回全部 3 位客户;CustomerID=3(Charlie)在 Orders 无匹配,对应 Product 为 NULL。 |
| RIGHT JOIN | 返回全部 3 笔订单;OrderID=103(CustomerID=4)在 Customers 无匹配,对应 Name 为 NULL。 |
| FULL OUTER JOIN | 返回 4 行完整并集;Charlie 的订单字段为 NULL,OrderID=103 的客户字段为 NULL。 |
| CROSS JOIN | 3 位客户与 3 笔订单两两组合,返回 9 行笛卡尔积。 |
| SELF JOIN | 同表按关联列(如 Staff.ManagerID = Manager.StaffID)自连接,映射上下级对应关系。 |
在本地 SQLite 3.53.1 对比七种 JOIN 类型与站点访问日志内连接
展开查看收起
"""Offline SQLite lab for SQL Chapter 18: JOIN overview."""
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()
# 1. Customers & Orders comparison across all JOIN types
cur.executescript(
"""
CREATE TABLE Customers (
CustomerID INT,
Name TEXT
);
INSERT INTO Customers VALUES
(1, 'Alice'),
(2, 'Bob'),
(3, 'Charlie');
CREATE TABLE Orders (
OrderID INT,
CustomerID INT,
Product TEXT
);
INSERT INTO Orders VALUES
(101, 1, 'Laptop'),
(102, 2, 'Phone'),
(103, 4, 'Tablet');
"""
)
inner_rows = [
list(r)
for r in cur.execute(
"""
SELECT c.CustomerID, c.Name, o.Product
FROM Customers c
INNER JOIN Orders o ON c.CustomerID = o.CustomerID
ORDER BY c.CustomerID
"""
).fetchall()
]
left_rows = [
list(r)
for r in cur.execute(
"""
SELECT c.CustomerID, c.Name, o.Product
FROM Customers c
LEFT JOIN Orders o ON c.CustomerID = o.CustomerID
ORDER BY c.CustomerID
"""
).fetchall()
]
right_rows = [
list(r)
for r in cur.execute(
"""
SELECT o.OrderID, c.Name, o.Product
FROM Customers c
RIGHT JOIN Orders o ON c.CustomerID = o.CustomerID
ORDER BY o.OrderID
"""
).fetchall()
]
full_rows = [
list(r)
for r in cur.execute(
"""
SELECT c.CustomerID, c.Name, o.OrderID, o.Product
FROM Customers c
FULL OUTER JOIN Orders o ON c.CustomerID = o.CustomerID
ORDER BY COALESCE(c.CustomerID, o.CustomerID)
"""
).fetchall()
]
cross_count = cur.execute(
"SELECT COUNT(*) FROM Customers CROSS JOIN Orders"
).fetchone()[0]
natural_rows = [
list(r)
for r in cur.execute(
"""
SELECT CustomerID, Name, OrderID, Product
FROM Customers NATURAL JOIN Orders
ORDER BY CustomerID
"""
).fetchall()
]
case1 = make_case(
"customers_orders_all_joins",
"Verify INNER, LEFT, RIGHT, FULL OUTER, CROSS, and NATURAL JOIN on Customers and Orders",
{
"inner": [[1, "Alice", "Laptop"], [2, "Bob", "Phone"]],
"left": [[1, "Alice", "Laptop"], [2, "Bob", "Phone"], [3, "Charlie", None]],
"right": [[101, "Alice", "Laptop"], [102, "Bob", "Phone"], [103, None, "Tablet"]],
"full": [
[1, "Alice", 101, "Laptop"],
[2, "Bob", 102, "Phone"],
[3, "Charlie", None, None],
[None, None, 103, "Tablet"],
],
"cross_count": 9,
"natural": [[1, "Alice", 101, "Laptop"], [2, "Bob", 102, "Phone"]],
},
{
"inner": inner_rows,
"left": left_rows,
"right": right_rows,
"full": full_rows,
"cross_count": cross_count,
"natural": natural_rows,
},
)
# 2. SELF JOIN hierarchy
cur.executescript(
"""
CREATE TABLE Staff (
StaffID INT,
Name TEXT,
ManagerID INT
);
INSERT INTO Staff VALUES
(1, 'Director', NULL),
(2, 'Alice', 1),
(3, 'Bob', 2);
"""
)
self_rows = [
list(r)
for r in cur.execute(
"""
SELECT e.Name AS employee, m.Name AS manager
FROM Staff e
LEFT JOIN Staff m ON e.ManagerID = m.StaffID
ORDER BY e.StaffID
"""
).fetchall()
]
case2 = make_case(
"self_join_hierarchy",
"Verify SELF JOIN pairing employees with their managers in the same table",
[["Director", None], ["Alice", "Director"], ["Bob", "Alice"]],
self_rows,
)
# 3. Websites & access_log INNER JOIN
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_join_rows = [
list(r)
for r in cur.execute(
"""
SELECT Websites.id, Websites.name, access_log.count, access_log.date
FROM Websites
INNER JOIN access_log ON Websites.id = access_log.site_id
ORDER BY access_log.aid
"""
).fetchall()
]
case3 = make_case(
"websites_access_log_inner_join",
"Verify INNER JOIN between Websites and access_log returns 9 matched rows and omits id=7",
{
"row_count": 9,
"first_row": [1, "Google", 45, "2016-05-10"],
"last_row": [3, "蓝色天空", 201, "2016-05-17"],
"distinct_ids": [1, 2, 3, 4, 5],
},
{
"row_count": len(site_join_rows),
"first_row": site_join_rows[0],
"last_row": site_join_rows[-1],
"distinct_ids": sorted({r[0] for r in site_join_rows}),
},
)
# 4. JOIN vs INNER JOIN equivalence
plain_join_rows = [
list(r)
for r in cur.execute(
"""
SELECT Websites.id, Websites.name, access_log.count, access_log.date
FROM Websites
JOIN access_log ON Websites.id = access_log.site_id
ORDER BY access_log.aid
"""
).fetchall()
]
case4 = make_case(
"join_syntax_equivalence",
"Verify plain JOIN produces the exact same result set as INNER JOIN",
True,
plain_join_rows == site_join_rows,
)
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 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
INNER JOIN 仅保留 CustomerID 为 1 和 2 的交集共 2 行;CROSS JOIN 产生两表笛卡尔积共 3×3=9 行。