"""SQL 快速参考离线实验:覆盖速查表中 DQL、过滤排序、分组聚合、四类 JOIN、UNION、DML 与 DDL 语句实测。"""
import json
import platform
import sqlite3
def run() -> dict:
conn = sqlite3.connect(":memory:")
cases = []
# Case 1: DDL lifecycle — CREATE TABLE, ALTER TABLE ADD/DROP COLUMN, CREATE/DROP INDEX, CREATE VIEW, DROP TABLE
conn.executescript(
"""
CREATE TABLE websites (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
alexa INTEGER NOT NULL,
country TEXT NOT NULL
);
ALTER TABLE websites ADD COLUMN note TEXT;
CREATE INDEX idx_websites_country ON websites (country);
CREATE UNIQUE INDEX idx_websites_name ON websites (name);
CREATE VIEW cn_sites AS SELECT id, name, alexa FROM websites WHERE country = 'CN';
"""
)
conn.executemany(
"INSERT INTO websites (id, name, alexa, country, note) VALUES (?, ?, ?, ?, ?);",
[
(1, "Google", 1, "USA", "search"),
(2, "淘宝", 13, "CN", "shop"),
(3, "蓝色天空", 4689, "CN", "docs"),
(4, "微博", 20, "CN", "social"),
(5, "Facebook", 3, "USA", "social"),
],
)
cols_with_note = [r[1] for r in conn.execute("PRAGMA table_info(websites);").fetchall()]
view_names = [r[0] for r in conn.execute("SELECT name FROM cn_sites ORDER BY alexa;").fetchall()]
conn.execute("DROP INDEX idx_websites_country;")
conn.execute("ALTER TABLE websites DROP COLUMN note;")
cols_after_drop = [r[1] for r in conn.execute("PRAGMA table_info(websites);").fetchall()]
conn.execute("CREATE TABLE scratch_tmp (k INTEGER);")
conn.execute("DROP TABLE scratch_tmp;")
tmp_exists = conn.execute(
"SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='scratch_tmp';"
).fetchone()[0]
exp1 = {
"cols_with_note": ["id", "name", "alexa", "country", "note"],
"cols_after_drop": ["id", "name", "alexa", "country"],
"cn_view_sorted": ["淘宝", "微博", "蓝色天空"],
"scratch_dropped": 0,
}
act1 = {
"cols_with_note": cols_with_note,
"cols_after_drop": cols_after_drop,
"cn_view_sorted": view_names,
"scratch_dropped": tmp_exists,
}
cases.append(
{
"name": "quickref_ddl_table_alter_index_view_drop",
"summary": "验证 CREATE TABLE、ALTER TABLE 增删列、CREATE/DROP INDEX、CREATE VIEW 与 DROP TABLE",
"expected": exp1,
"actual": act1,
"passed": act1 == exp1,
}
)
# Case 2: DQL filtering, aliases, DISTINCT, BETWEEN, IN, LIKE, AND/OR, ORDER BY, LIMIT (TOP equiv)
distinct_c = [
r[0] for r in conn.execute("SELECT DISTINCT country FROM websites ORDER BY country;").fetchall()
]
between_rows = [
r[0] for r in conn.execute("SELECT name FROM websites WHERE alexa BETWEEN 1 AND 20 ORDER BY alexa;").fetchall()
]
in_and_like = [
list(r)
for r in conn.execute(
"""
SELECT w.name AS site_name, w.country AS region
FROM websites AS w
WHERE w.country IN ('USA', 'CN')
AND (w.name LIKE 'G%' OR w.name LIKE 'F%')
ORDER BY w.alexa ASC
LIMIT 2;
"""
).fetchall()
]
exp2 = {
"distinct_countries": ["CN", "USA"],
"between_1_20": ["Google", "Facebook", "淘宝", "微博"],
"alias_in_like_and_or_limit": [["Google", "USA"], ["Facebook", "USA"]],
}
act2 = {
"distinct_countries": distinct_c,
"between_1_20": between_rows,
"alias_in_like_and_or_limit": in_and_like,
}
cases.append(
{
"name": "quickref_dql_where_between_in_like_order",
"summary": "验证 SELECT、DISTINCT、AS 别名、WHERE、AND/OR、BETWEEN、IN、LIKE、ORDER BY 与 LIMIT",
"expected": exp2,
"actual": act2,
"passed": act2 == exp2,
}
)
# Case 3: GROUP BY, HAVING, INNER/LEFT/RIGHT/FULL JOIN, UNION vs UNION ALL
conn.executescript(
"""
CREATE TABLE access_log (
aid INTEGER PRIMARY KEY,
site_id INTEGER NOT NULL,
count INTEGER NOT NULL
);
INSERT INTO access_log (aid, site_id, count) VALUES
(1, 1, 275),
(2, 3, 521),
(3, 5, 750),
(4, 99, 12);
"""
)
having_rows = [
list(r)
for r in conn.execute(
"""
SELECT country, COUNT(*) AS cnt
FROM websites
GROUP BY country
HAVING COUNT(*) >= 2
ORDER BY country;
"""
).fetchall()
]
inner_cnt = conn.execute(
"SELECT COUNT(*) FROM websites INNER JOIN access_log ON websites.id = access_log.site_id;"
).fetchone()[0]
left_cnt = conn.execute(
"SELECT COUNT(*) FROM websites LEFT JOIN access_log ON websites.id = access_log.site_id;"
).fetchone()[0]
right_cnt = conn.execute(
"SELECT COUNT(*) FROM websites RIGHT JOIN access_log ON websites.id = access_log.site_id;"
).fetchone()[0]
full_cnt = conn.execute(
"SELECT COUNT(*) FROM websites FULL OUTER JOIN access_log ON websites.id = access_log.site_id;"
).fetchone()[0]
union_cnt = conn.execute(
"SELECT country FROM websites WHERE id <= 3 UNION SELECT country FROM websites WHERE id >= 3;"
).fetchall()
union_all_cnt = conn.execute(
"SELECT country FROM websites WHERE id <= 3 UNION ALL SELECT country FROM websites WHERE id >= 3;"
).fetchall()
exp3 = {
"group_having": [["CN", 3], ["USA", 2]],
"join_counts": {"inner": 3, "left": 5, "right": 4, "full": 6},
"union_rows": 2,
"union_all_rows": 6,
}
act3 = {
"group_having": having_rows,
"join_counts": {
"inner": inner_cnt,
"left": left_cnt,
"right": right_cnt,
"full": full_cnt,
},
"union_rows": len(union_cnt),
"union_all_rows": len(union_all_cnt),
}
cases.append(
{
"name": "quickref_group_having_joins_union",
"summary": "验证 GROUP BY/HAVING、INNER/LEFT/RIGHT/FULL JOIN 行数差异及 UNION 与 UNION ALL 去重对比",
"expected": exp3,
"actual": act3,
"passed": act3 == exp3,
}
)
# Case 4: DML INSERT INTO, UPDATE, DELETE, CTAS (SELECT INTO equiv), and DELETE all (TRUNCATE equiv)
conn.execute("CREATE TABLE websites_copy AS SELECT id, name, alexa FROM websites;")
conn.execute("INSERT INTO websites_copy (id, name, alexa) VALUES (6, '知乎', 180);")
conn.execute("UPDATE websites_copy SET alexa = 150 WHERE id = 6;")
updated_alexa = conn.execute("SELECT alexa FROM websites_copy WHERE id = 6;").fetchone()[0]
conn.execute("DELETE FROM websites_copy WHERE id = 6;")
after_one_del = conn.execute("SELECT COUNT(*) FROM websites_copy;").fetchone()[0]
conn.execute("DELETE FROM websites_copy;")
after_all_del = conn.execute("SELECT COUNT(*) FROM websites_copy;").fetchone()[0]
exp4 = {
"updated_alexa": 150,
"after_single_delete": 5,
"after_delete_all": 0,
}
act4 = {
"updated_alexa": updated_alexa,
"after_single_delete": after_one_del,
"after_delete_all": after_all_del,
}
cases.append(
{
"name": "quickref_dml_insert_update_delete_copy",
"summary": "验证 INSERT INTO、UPDATE、条件 DELETE、表复制(CREATE TABLE AS SELECT)与全表清空",
"expected": exp4,
"actual": act4,
"passed": act4 == exp4,
}
)
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-quickref-lab/explore-quickref.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-quickref.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联67章) · 含当前章节或实例 · mbskycom202612a1523.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1574.zip