"""MySQL JOIN 连接离线实验:在内存 SQLite 3.53 中实测 INNER JOIN、多表连接、LEFT JOIN、RIGHT JOIN 及其表顺序交换等价性、WHERE 隐式连接以及文章表与作者统计表联查。"""
import json
import platform
import sqlite3
def build_db() -> sqlite3.Connection:
conn = sqlite3.connect(":memory:")
conn.executescript(
"""
CREATE TABLE customers (customer_id INTEGER PRIMARY KEY, customer_name TEXT NOT NULL);
INSERT INTO customers VALUES (1, 'Alice'), (2, 'Bob'), (3, 'Carol');
CREATE TABLE orders (order_id INTEGER PRIMARY KEY, customer_id INTEGER, order_date TEXT);
INSERT INTO orders VALUES
(101, 1, '2023-05-10'),
(102, 2, '2022-11-20'),
(103, 99, '2023-08-01');
CREATE TABLE products (product_id INTEGER PRIMARY KEY, product_name TEXT NOT NULL);
INSERT INTO products VALUES (10, 'Keyboard'), (20, 'Monitor');
CREATE TABLE order_items (item_id INTEGER PRIMARY KEY, order_id INTEGER, product_id INTEGER);
INSERT INTO order_items VALUES (1, 101, 10), (2, 101, 20);
CREATE TABLE author_counts_tbl (article_author TEXT NOT NULL, login_count INTEGER NOT NULL);
INSERT INTO author_counts_tbl VALUES
('蓝色天空', 10),
('MBSKY.COM', 20),
('Google', 22);
CREATE TABLE articles_tbl (
article_id INTEGER PRIMARY KEY,
article_title TEXT NOT NULL,
article_author TEXT NOT NULL,
submission_date TEXT NOT NULL
);
INSERT INTO articles_tbl VALUES
(1, '学习 PHP', '蓝色天空', '2017-04-12'),
(2, '学习 MySQL', '蓝色天空', '2017-04-12'),
(3, '学习 Java', 'MBSKY.COM', '2015-05-01'),
(4, '学习 Python', 'MBSKY.COM', '2016-03-06'),
(5, '学习 C', 'FK', '2017-04-05');
"""
)
return conn
def run() -> dict:
conn = build_db()
cases = []
# Case 1: INNER JOIN (simple, alias, 4-table join, WHERE filter)
inner_simple = [
list(r)
for r in conn.execute(
"""
SELECT o.order_id, c.customer_name
FROM orders AS o
INNER JOIN customers AS c ON o.customer_id = c.customer_id
ORDER BY o.order_id;
"""
).fetchall()
]
inner_4tbl = [
list(r)
for r in conn.execute(
"""
SELECT orders.order_id, customers.customer_name, products.product_name
FROM orders
INNER JOIN customers ON orders.customer_id = customers.customer_id
INNER JOIN order_items ON orders.order_id = order_items.order_id
INNER JOIN products ON order_items.product_id = products.product_id
ORDER BY products.product_id;
"""
).fetchall()
]
inner_where = [
list(r)
for r in conn.execute(
"""
SELECT orders.order_id, customers.customer_name
FROM orders
INNER JOIN customers ON orders.customer_id = customers.customer_id
WHERE orders.order_date >= '2023-01-01';
"""
).fetchall()
]
exp1 = {
"inner_simple": [[101, "Alice"], [102, "Bob"]],
"inner_4tbl": [[101, "Alice", "Keyboard"], [101, "Alice", "Monitor"]],
"inner_where_2023": [[101, "Alice"]],
}
act1 = {
"inner_simple": inner_simple,
"inner_4tbl": inner_4tbl,
"inner_where_2023": inner_where,
}
cases.append(
{
"name": "inner_join_alias_multitable_and_where",
"summary": "实测订单/客户/明细/商品的 INNER JOIN、表别名、四表连接及日期 WHERE 过滤",
"expected": exp1,
"actual": act1,
"passed": act1 == exp1,
}
)
# Case 2: LEFT JOIN (simple, 4-table, WHERE retaining unmatched via IS NULL)
left_simple = [
list(r)
for r in conn.execute(
"""
SELECT c.customer_id, c.customer_name, o.order_id
FROM customers AS c
LEFT JOIN orders AS o ON c.customer_id = o.customer_id
ORDER BY c.customer_id;
"""
).fetchall()
]
left_4tbl = [
list(r)
for r in conn.execute(
"""
SELECT customers.customer_id, orders.order_id, products.product_name
FROM customers
LEFT JOIN orders ON customers.customer_id = orders.customer_id
LEFT JOIN order_items ON orders.order_id = order_items.order_id
LEFT JOIN products ON order_items.product_id = products.product_id
ORDER BY customers.customer_id, products.product_id;
"""
).fetchall()
]
left_where = [
list(r)
for r in conn.execute(
"""
SELECT customers.customer_id, customers.customer_name, orders.order_id
FROM customers
LEFT JOIN orders ON customers.customer_id = orders.customer_id
WHERE orders.order_date >= '2023-01-01' OR orders.order_id IS NULL
ORDER BY customers.customer_id;
"""
).fetchall()
]
exp2 = {
"left_simple": [[1, "Alice", 101], [2, "Bob", 102], [3, "Carol", None]],
"left_4tbl": [
[1, 101, "Keyboard"],
[1, 101, "Monitor"],
[2, 102, None],
[3, None, None],
],
"left_where_2023_or_null": [[1, "Alice", 101], [3, "Carol", None]],
}
act2 = {
"left_simple": left_simple,
"left_4tbl": left_4tbl,
"left_where_2023_or_null": left_where,
}
cases.append(
{
"name": "left_join_multitable_and_null_filter",
"summary": "实测 LEFT JOIN 保留无订单客户(右列为 NULL)、四表左连接及带 IS NULL 的过滤条件",
"expected": exp2,
"actual": act2,
"passed": act2 == exp2,
}
)
# Case 3: RIGHT JOIN and exact symmetry with swapped LEFT JOIN
right_res = [
list(r)
for r in conn.execute(
"""
SELECT customers.customer_id, orders.order_id
FROM customers
RIGHT JOIN orders ON customers.customer_id = orders.customer_id
ORDER BY orders.order_id;
"""
).fetchall()
]
swapped_left_res = [
list(r)
for r in conn.execute(
"""
SELECT customers.customer_id, orders.order_id
FROM orders
LEFT JOIN customers ON orders.customer_id = customers.customer_id
ORDER BY orders.order_id;
"""
).fetchall()
]
exp3 = {
"right_join_rows": [[1, 101], [2, 102], [None, 103]],
"swapped_left_equals_right": True,
}
act3 = {
"right_join_rows": right_res,
"swapped_left_equals_right": right_res == swapped_left_res,
}
cases.append(
{
"name": "right_join_and_swapped_left_symmetry",
"summary": "实测 RIGHT JOIN 保留右表孤立订单(左列为 NULL)并验证与交换表顺序的 LEFT JOIN 完全等价",
"expected": exp3,
"actual": act3,
"passed": act3 == exp3,
}
)
# Case 4: Sample two-table demo (articles_tbl & author_counts_tbl): INNER, WHERE equiv, LEFT, RIGHT
demo_inner = [
list(r)
for r in conn.execute(
"""
SELECT a.article_id, a.article_author, b.login_count
FROM articles_tbl a
INNER JOIN author_counts_tbl b ON a.article_author = b.article_author
ORDER BY a.article_id;
"""
).fetchall()
]
demo_where = [
list(r)
for r in conn.execute(
"""
SELECT a.article_id, a.article_author, b.login_count
FROM articles_tbl a, author_counts_tbl b
WHERE a.article_author = b.article_author
ORDER BY a.article_id;
"""
).fetchall()
]
demo_left = [
list(r)
for r in conn.execute(
"""
SELECT a.article_id, a.article_author, b.login_count
FROM articles_tbl a
LEFT JOIN author_counts_tbl b ON a.article_author = b.article_author
ORDER BY a.article_id;
"""
).fetchall()
]
demo_right = [
list(r)
for r in conn.execute(
"""
SELECT a.article_id, a.article_author, b.login_count
FROM articles_tbl a
RIGHT JOIN author_counts_tbl b ON a.article_author = b.article_author
ORDER BY COALESCE(a.article_id, 999);
"""
).fetchall()
]
exp4 = {
"inner_count": 4,
"where_equals_inner": True,
"left_join_unmatched_row": [5, "FK", None],
"right_join_unmatched_row": [None, None, 22],
}
act4 = {
"inner_count": len(demo_inner),
"where_equals_inner": demo_inner == demo_where,
"left_join_unmatched_row": demo_left[-1],
"right_join_unmatched_row": demo_right[-1],
}
cases.append(
{
"name": "articles_and_author_counts_all_joins",
"summary": "在双演示表上对照 INNER JOIN、WHERE 等值连接、LEFT JOIN(含未匹配 FK)与 RIGHT JOIN(含未匹配 22)",
"expected": exp4,
"actual": act4,
"passed": act4 == exp4,
}
)
conn.close()
return {
"version": f"CPython {platform.python_version()} / SQLite {sqlite3.sqlite_version} (offline MySQL verifier)",
"cases": cases,
}
if __name__ == "__main__":
print(json.dumps(run(), ensure_ascii=False, indent=2))
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/mysql-join-lab/explore-join.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-join.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联41章) · 含当前章节或实例 · mbskycom202612a1590.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1610.zip