"""SQL EXISTS 离线实验:验证 EXISTS / NOT EXISTS 相关子查询、空值安全语义及与 IN / NOT IN 对比。"""
import json
import platform
import sqlite3
def seed_tables(conn: sqlite3.Connection) -> None:
conn.executescript(
"""
CREATE TABLE websites (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
url TEXT NOT NULL,
alexa INTEGER NOT NULL,
country TEXT NOT NULL
);
INSERT INTO websites (id, name, url, alexa, country) VALUES
(1, 'Google', 'https://www.google.com/', 1, 'USA'),
(2, '淘宝', 'https://www.taobao.com/', 13, 'CN'),
(3, '蓝色天空', 'http://www.mbsky.com/', 4689, 'CN'),
(4, '微博', 'http://weibo.com/', 20, 'CN'),
(5, 'Facebook', 'https://www.facebook.com/', 3, 'USA');
CREATE TABLE access_log (
aid INTEGER PRIMARY KEY,
site_id INTEGER,
count INTEGER NOT NULL,
date TEXT NOT NULL
);
INSERT INTO access_log (aid, site_id, count, date) 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');
"""
)
def run() -> dict:
conn = sqlite3.connect(":memory:")
seed_tables(conn)
cases = []
# Case 1: WHERE EXISTS correlated subquery (single record count > 200)
rows1 = [
list(r)
for r in conn.execute(
"""
SELECT websites.name, websites.url
FROM websites
WHERE EXISTS (
SELECT count FROM access_log
WHERE websites.id = access_log.site_id AND count > 200
)
ORDER BY websites.id;
"""
).fetchall()
]
exp1 = [
["Google", "https://www.google.com/"],
["蓝色天空", "http://www.mbsky.com/"],
["Facebook", "https://www.facebook.com/"],
]
cases.append(
{
"name": "exists_correlated_subquery",
"summary": "执行 WHERE EXISTS 相关子查询找出存在单次访问量大于 200 记录的 3 个站点",
"expected": exp1,
"actual": rows1,
"passed": rows1 == exp1,
}
)
# Case 2: WHERE NOT EXISTS correlated subquery
rows2 = [
list(r)
for r in conn.execute(
"""
SELECT websites.name, websites.url
FROM websites
WHERE NOT EXISTS (
SELECT count FROM access_log
WHERE websites.id = access_log.site_id AND count > 200
)
ORDER BY websites.id;
"""
).fetchall()
]
exp2 = [
["淘宝", "https://www.taobao.com/"],
["微博", "http://weibo.com/"],
]
cases.append(
{
"name": "not_exists_correlated_subquery",
"summary": "执行 WHERE NOT EXISTS 找出不存在单次访问量大于 200 记录的 2 个站点",
"expected": exp2,
"actual": rows2,
"passed": rows2 == exp2,
}
)
# Case 3: NOT EXISTS vs NOT IN when subquery contains NULL, plus SELECT 1 equivalence
conn.execute(
"INSERT INTO access_log (aid, site_id, count, date) VALUES (10, NULL, 999, '2016-05-18');"
)
not_in_rows = [
r[0]
for r in conn.execute(
"SELECT name FROM websites WHERE id NOT IN (SELECT site_id FROM access_log WHERE count > 200) ORDER BY id;"
).fetchall()
]
not_exists_rows = [
r[0]
for r in conn.execute(
"SELECT name FROM websites WHERE NOT EXISTS (SELECT 1 FROM access_log WHERE websites.id = access_log.site_id AND count > 200) ORDER BY id;"
).fetchall()
]
exp3 = {
"not_in_with_null_subquery": [],
"not_exists_with_null_subquery": ["淘宝", "微博"],
}
act3 = {
"not_in_with_null_subquery": not_in_rows,
"not_exists_with_null_subquery": not_exists_rows,
}
cases.append(
{
"name": "not_exists_null_safety_vs_not_in",
"summary": "验证子查询包含 NULL 时 NOT IN 返回空集而 NOT EXISTS (SELECT 1 ...) 仍保持正确语义",
"expected": exp3,
"actual": act3,
"passed": act3 == exp3,
}
)
conn.close()
return {
"version": f"CPython {platform.python_version()} / SQLite {sqlite3.sqlite_version}",
"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/sql-exists-lab/explore-exists.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-exists.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1538.zip
课程关联工程包(登记关联67章) · 含当前章节或实例 · mbskycom202612a1523.zip