SQL INNER JOIN
详解 SQL INNER JOIN 内连接语法、与简写 JOIN 的等价性、Students/Enrollments 交集过滤逻辑及 Websites/access_log 排序关联查询,并在本地 SQLite 3.53.1 实测验证。
学完这一章,你能够
- 详解 SQL INNER JOIN 内连接语法、与简写 JOIN 的等价性、Students/Enrollments 交集过滤逻辑及 Websites/access_log 排序关联查询,并在本地 SQLite 3.53.1 实测验证。
INNER JOIN 语义与标准语法
`INNER JOIN` 是 SQL 中使用频率最高的表连接方式,用来依据表之间的关联条件提取同时存在于多张表中的匹配记录,从集合角度对应两个表在连接键上的交集。
其标准语法为 `SELECT columns FROM table1 INNER JOIN table2 ON table1.column_name = table2.column_name;`,其中 `INNER` 关键字可以省略,直接写 `JOIN` 与 `INNER JOIN` 语义完全相同。语法中 `columns` 指定要投影输出的列,`table1` 与 `table2` 为待连接的表名,`column_name` 为两表建立关联的公共列。本地 SQLite 3.53.1 实测确认两种写法在选课数据上输出完全一致。
学生选课表交集实例分析
设有 `Students` 表(含 1-Alice、2-Bob、3-Charlie)和 `Enrollments` 表(含 101-1-Math、102-2-Science、103-4-History)。执行 `SELECT Students.Name, Enrollments.Course FROM Students INNER JOIN Enrollments ON Students.StudentID = Enrollments.StudentID;` 时,仅当两表的 `StudentID` 相等才会生成输出行。SQLite 3.53.1 实测精确返回 2 条记录:`['Alice', 'Math']` 与 `['Bob', 'Science']`;未选课的 Charlie(StudentID=3)与无对应学生记录的 History(EnrollmentID=103,StudentID=4)均被排除。
站点与访问日志排序内连接实战
在示例数据库包含 6 条站点的 `Websites` 表与 9 条访问记录的 `access_log` 表上,利用 `Websites.id = access_log.site_id` 可以把站点名称与对应的访问量、访问日期拼接在一起。
运行 `SELECT 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.count;` 后,SQLite 3.53.1 实测按访问次数升序返回 9 条记录:访问量最低为 `['淘宝', 10, '2016-05-14']`,最高为 `['Facebook', 545, '2016-05-16']`,完整访问序列为 `[10, 13, 45, 100, 201, 205, 220, 230, 545]`;由于 id=7 的 `stackoverflow` 在 `access_log` 中无匹配行,结果中不会列出该站点。
示例表:Students
| StudentID | Name | Age |
| 1 | Alice | 22 |
| 2 | Bob | 23 |
| 3 | Charlie | 24 |
示例表:Enrollments
| EnrollmentID | StudentID | Course |
| 101 | 1 | Math |
| 102 | 2 | Science |
| 103 | 4 | History |
Students INNER JOIN Enrollments 查询结果
| Name | Course |
| Alice | Math |
| Bob | Science |
在本地 SQLite 3.53.1 验证 INNER JOIN/JOIN 等价性、未匹配排除与排序连接
展开查看收起
"""Offline SQLite lab for SQL Chapter 19: INNER 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,
Age INT
);
INSERT INTO Students VALUES
(1, 'Alice', 22),
(2, 'Bob', 23),
(3, 'Charlie', 24);
CREATE TABLE Enrollments (
EnrollmentID INT,
StudentID INT,
Course TEXT
);
INSERT INTO Enrollments VALUES
(101, 1, 'Math'),
(102, 2, 'Science'),
(103, 4, 'History');
"""
)
inner_res = [
list(r)
for r in cur.execute(
"""
SELECT Students.Name, Enrollments.Course
FROM Students
INNER JOIN Enrollments
ON Students.StudentID = Enrollments.StudentID
ORDER BY Students.StudentID
"""
).fetchall()
]
short_join_res = [
list(r)
for r in cur.execute(
"""
SELECT Students.Name, Enrollments.Course
FROM Students
JOIN Enrollments
ON Students.StudentID = Enrollments.StudentID
ORDER BY Students.StudentID
"""
).fetchall()
]
case1 = make_case(
"inner_join_vs_join_syntax",
"Verify INNER JOIN and shorthand JOIN yield identical matched rows on Students and Enrollments",
{
"inner_rows": [["Alice", "Math"], ["Bob", "Science"]],
"same_as_join": True,
},
{
"inner_rows": inner_res,
"same_as_join": inner_res == short_join_res,
},
)
matched_names = [r[0] for r in inner_res]
matched_courses = [r[1] for r in inner_res]
case2 = make_case(
"students_enrollments_exclusion",
"Verify unmatched rows (Charlie with StudentID=3 and History with StudentID=4) are excluded",
{
"row_count": 2,
"charlie_included": False,
"history_included": False,
},
{
"row_count": len(inner_res),
"charlie_included": "Charlie" in matched_names,
"history_included": "History" in matched_courses,
},
)
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');
"""
)
ordered_rows = [
list(r)
for r in cur.execute(
"""
SELECT 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.count
"""
).fetchall()
]
case3 = make_case(
"websites_access_log_ordered",
"Verify Websites INNER JOIN access_log ordered ascending by count excludes stackoverflow",
{
"row_count": 9,
"min_row": ["淘宝", 10, "2016-05-14"],
"max_row": ["Facebook", 545, "2016-05-16"],
"counts": [10, 13, 45, 100, 201, 205, 220, 230, 545],
"has_stackoverflow": False,
},
{
"row_count": len(ordered_rows),
"min_row": ordered_rows[0],
"max_row": ordered_rows[-1],
"counts": [r[1] for r in ordered_rows],
"has_stackoverflow": any(r[0] == "stackoverflow" for r in ordered_rows),
},
)
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()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
二者在标准 SQL 中完全等价;当左表某行在右表中找不到满足 ON 条件的记录时,该行不会出现在 INNER JOIN 的结果集中。