SQL SELECT DISTINCT
核对 SELECT DISTINCT 单列去重、多列组合去重以及 NULL 与 COUNT(DISTINCT) 聚合行为,并在本地 SQLite 中实测验证。
学完这一章,你能够
- 核对 SELECT DISTINCT 单列去重、多列组合去重以及 NULL 与 COUNT(DISTINCT) 聚合行为,并在本地 SQLite 中实测验证。
SELECT DISTINCT 语法与去重机制
数据表的某一列经常存在大量重复取值,当只需列出所有互不相同的值时,可在 `SELECT` 后紧跟 `DISTINCT` 关键词,语法为 `SELECT DISTINCT column1, column2, ... FROM table_name;`。其中 `column1, column2, ...` 指定需要去重输出的字段列表,`table_name` 为目标表名。需特别留意:当指定多列时,`DISTINCT` 作用于整个选中列元组(整行组合),而非仅对第一个字段去重。
单列去重、多列组合与 NULL 处理实测
在 5 行 `websites` 演示表中,`country` 列包含 3 条 `'CN'` 与 2 条 `'USA'`。执行 `SELECT DISTINCT country FROM websites;` 即可剔除重复项,仅返回 `['CN', 'USA']` 两行唯一结果。本站 SQLite 3.53.1 实测进一步验证了两类边界场景:一是在 `channels` 表上对 `(country, tier)` 执行多列 `SELECT DISTINCT`,5 条原始记录准确归并为 `[['CN', 'A'], ['CN', 'B'], ['USA', 'A']]` 3 个唯一组合;二是向 `websites` 插入两条 `country` 为 `NULL` 的草稿行后,`SELECT DISTINCT country` 将多个 `NULL` 合并为 1 行返回(`[None, 'CN', 'USA']`),而 `COUNT(DISTINCT country)` 遵循 SQL 聚合规则忽略 `NULL`,返回 `2`。
运行 SQLite 3.53 单列去重、多列元组去重及 NULL/COUNT(DISTINCT) 实测
"""SQL SELECT DISTINCT 离线实验:验证单列去重、多列组合去重以及 NULL 与 COUNT(DISTINCT) 行为。"""
import json
import platform
import sqlite3
def run() -> dict:
conn = sqlite3.connect(":memory:")
conn.executescript(
"""
CREATE TABLE websites (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
url TEXT NOT NULL,
alexa INTEGER NOT NULL,
country TEXT
);
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');
"""
)
cases = []
# Case 1: Single-column DISTINCT vs non-DISTINCT
raw_countries = [
r[0] for r in conn.execute("SELECT country FROM websites ORDER BY id;").fetchall()
]
distinct_countries = [
r[0]
for r in conn.execute(
"SELECT DISTINCT country FROM websites ORDER BY country ASC;"
).fetchall()
]
exp1 = {
"raw_count": 5,
"distinct_count": 2,
"distinct_values": ["CN", "USA"],
}
act1 = {
"raw_count": len(raw_countries),
"distinct_count": len(distinct_countries),
"distinct_values": distinct_countries,
}
cases.append(
{
"name": "select_distinct_single_column",
"summary": "对比 SELECT country 与 SELECT DISTINCT country,验证 5 行去重为 CN 与 USA 2 个唯一值",
"expected": exp1,
"actual": act1,
"passed": act1 == exp1,
}
)
# Case 2: Multi-column DISTINCT operates on tuple combinations
conn.executescript(
"""
CREATE TABLE channels (
id INTEGER PRIMARY KEY,
country TEXT,
tier TEXT
);
INSERT INTO channels VALUES
(1, 'CN', 'A'),
(2, 'CN', 'A'),
(3, 'CN', 'B'),
(4, 'USA', 'A'),
(5, 'USA', 'A');
"""
)
combos = [
list(r)
for r in conn.execute(
"SELECT DISTINCT country, tier FROM channels ORDER BY country, tier;"
).fetchall()
]
exp2 = [["CN", "A"], ["CN", "B"], ["USA", "A"]]
act2 = combos
cases.append(
{
"name": "select_distinct_multi_column",
"summary": "验证多列 SELECT DISTINCT 作用于整组列值组合而非仅首列",
"expected": exp2,
"actual": act2,
"passed": act2 == exp2,
}
)
# Case 3: DISTINCT with multiple NULLs and COUNT(DISTINCT col)
conn.execute(
"INSERT INTO websites (name, url, alexa, country) VALUES ('DraftA', 'https://a.example/', 100, NULL);"
)
conn.execute(
"INSERT INTO websites (name, url, alexa, country) VALUES ('DraftB', 'https://b.example/', 101, NULL);"
)
distinct_with_null = [
r[0]
for r in conn.execute(
"SELECT DISTINCT country FROM websites ORDER BY country ASC;"
).fetchall()
]
count_distinct = conn.execute(
"SELECT COUNT(DISTINCT country) FROM websites;"
).fetchone()[0]
exp3 = {
"distinct_rows_including_null": [None, "CN", "USA"],
"count_distinct_non_null": 2,
}
act3 = {
"distinct_rows_including_null": distinct_with_null,
"count_distinct_non_null": count_distinct,
}
cases.append(
{
"name": "select_distinct_with_null_and_count",
"summary": "验证多个 NULL 在 SELECT DISTINCT 中合并为一行且 COUNT(DISTINCT) 忽略 NULL",
"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))
- 验证 websites.country 从 5 行去重为 ['CN', 'USA']、多列组合去重为 3 组、多个 NULL 归并为一行且 COUNT(DISTINCT) 忽略 NULL 返回 2。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:1078d869472f695b6e93cf75d3d6342037b5d7ed85976ceec12be643c6088bfd
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:68da1f6a3b98939d125f6c8a15c2691f09d6411662bdcf19361bf4312d0a936e
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
执行 `SELECT DISTINCT country, tier FROM channels` 时,若存在 `('CN', 'A')` 和 `('CN', 'B')` 两行,结果会保留几行?
展开参考解答
会保留 2 行。`DISTINCT` 作用于选中列组成的整行元组,两行的 `tier` 不同,因此组合互异均会保留。