MySQL 索引
系统讲解 MySQL 索引的加速原理与写入代价、普通索引/唯一索引/主键/全文索引的三种创建与删除语法、组合索引最左前缀匹配,以及 SHOW INDEX 元数据查看与本地 SQLite 查询计划实测。
学完这一章,你能够
- 系统讲解 MySQL 索引的加速原理与写入代价、普通索引/唯一索引/主键/全文索引的三种创建与删除语法、组合索引最左前缀匹配,以及 SHOW INDEX 元数据查看与本地 SQLite 查询计划实测。
索引原理、单列与组合索引及权衡代价
MySQL 索引是一种有序数据结构(InnoDB 默认采用 B+Tree),作用类似于书籍或字典的检索目录:通过维护索引键到数据行的快速定位路径,使数据库无需全表逐行扫描即可命中目标记录,在大表查询场景下可带来数量级的检索加速。
按覆盖列数划分,索引可分为单列索引(单个索引仅含 1 列,一张表可建多个)与组合索引(单个索引依次包含多列,查询遵循最左前缀原则)。索引应优先建在高频出现在 `WHERE` 过滤、`JOIN` 连接和 `ORDER BY` 排序中的列上。需同时权衡三项成本:索引本身占用额外磁盘与缓冲池空间;每次 `INSERT`/`UPDATE`/`DELETE` 都要同步维护索引树结构从而拖慢写入;过多或低选择度索引反而会增加优化器决策负担与写放大。
普通索引的三种创建方式与两种删除语法
普通索引(允许重复值)最常见的创建方式是使用独立语句 `CREATE INDEX index_name ON table_name (column1 [ASC|DESC], ...);`,其中索引名在同一表内唯一,可指定单列或多列及升序/降序(MySQL 8.0 起真正支持降序索引)。例如在 `students(name)` 上创建 `idx_name` 后,本地 SQLite 3.53.1 通过 `EXPLAIN QUERY PLAN` 实测确认查询计划由 `SCAN students` 切换为 `SEARCH students USING INDEX idx_name`。大表建索引虽会消耗一定构建时间,但建成后检索效率显著提升。
第二种方式是在已有表上通过 `ALTER TABLE table_name ADD INDEX index_name (column1 [ASC|DESC], ...);` 追加索引(例如 `ALTER TABLE employees ADD INDEX idx_age (age);`)。
第三种方式是在建表时直接内联声明:`CREATE TABLE students (id INT PRIMARY KEY, name VARCHAR(50), age INT, INDEX idx_age (age));`,一步完成表结构与索引定义。
删除普通索引(或唯一索引)有两种等价写法:`DROP INDEX index_name ON table_name;` 与 `ALTER TABLE table_name DROP INDEX index_name;`。若目标索引不存在,直接删除会抛出错误,因此运维脚本应先检查索引目录或妥善捕获异常(本地 SQLite 3.53.1 实测重复 `DROP INDEX idx_age` 触发 `OperationalError`)。
唯一索引的三种创建方式与 NULL 唯一性规则
唯一索引不仅加速查询,还强制索引列(或列组合)的值不可重复。独立创建语法为 `CREATE UNIQUE INDEX idx_email ON employees (email);`,常用于邮箱、手机号或业务唯一编码列。
对已有表亦可通过 `ALTER TABLE employees ADD CONSTRAINT idx_email UNIQUE (email);` 添加命名唯一约束(底层自动建立对应唯一索引);若表中已存在重复 `email`,该操作会直接失败,需先清理重复数据。
建表时既可在列后简写 `email VARCHAR(100) UNIQUE`(由数据库自动生成索引名),也可在表尾用 `CONSTRAINT index_name UNIQUE (column1, ...)` 显式命名。特别注意:在 MySQL(及 SQLite)中,唯一索引允许出现多个 `NULL` 值,因为 `NULL` 表示未知而不视为彼此相等——本地 SQLite 3.53.1 实测确认插入重复邮箱报错,但连续插入两条 `email IS NULL` 记录均成功。
ALTER 增删四类索引/主键与 SHOW INDEX 查看
汇总而言,`ALTER TABLE` 支持四类索引添加:`ADD PRIMARY KEY (column_list)`(值唯一且不可为 `NULL`)、`ADD UNIQUE index_name (column_list)`(非空值唯一,允许多个 `NULL`)、`ADD INDEX index_name (column_list)`(普通索引,允许重复)以及 `ADD FULLTEXT index_name (column_list)`(全文索引,用于文本分词检索)。对应删除普通/唯一/全文索引均使用 `ALTER TABLE tbl DROP INDEX index_name;`。
通过 `ALTER TABLE` 补加主键前须确保目标列均为 `NOT NULL`(如先 `MODIFY i INT NOT NULL` 再 `ADD PRIMARY KEY (i)`)。删除主键时因每张表至多只有一个主键,直接写 `ALTER TABLE tbl DROP PRIMARY KEY;` 即可,无需指定索引名(注意若主键列带有 `AUTO_INCREMENT`,需先移除自增属性才能删主键)。
排查索引定义与基数时使用 `SHOW INDEX FROM table_name\G`,其中 `\G` 将宽表按纵列展开便于阅读,核心输出字段包括 `Key_name`(索引名)、`Column_name`(列名)、`Non_unique`(`0` 为唯一索引,`1` 为非唯一)、`Collation`(排序方向)和 `Cardinality`(唯一值基数估算)。本地 SQLite 3.53.1 通过 `PRAGMA index_list`/`index_info` 实测检出唯一索引元数据,并验证了组合索引 `(dept, age)` 对前导列走索引、对非前导列 `age` 退化为全表扫描的差异。
在本地 SQLite 3.53.1 实测普通/唯一/组合索引、EXPLAIN QUERY PLAN 与索引元数据
"""Offline SQLite verifier for MySQL Chapter 25: Indexes (normal, unique, composite, EXPLAIN QUERY PLAN)."""
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()
# 1. Normal index creation, EXPLAIN QUERY PLAN, and DROP INDEX
cur.executescript(
"""
CREATE TABLE students (
id INT PRIMARY KEY,
name TEXT,
age INT
);
INSERT INTO students VALUES
(1, 'Alice', 20), (2, 'Bob', 22), (3, 'Carol', 21), (4, 'David', 22);
"""
)
plan_before = cur.execute(
"EXPLAIN QUERY PLAN SELECT * FROM students WHERE name = 'Alice'"
).fetchone()[3]
cur.execute("CREATE INDEX idx_name ON students (name)")
cur.execute("CREATE INDEX idx_age ON students (age)")
plan_after = cur.execute(
"EXPLAIN QUERY PLAN SELECT * FROM students WHERE name = 'Alice'"
).fetchone()[3]
idx_before_drop = sorted(
r[1] for r in cur.execute("PRAGMA index_list(students)").fetchall() if not r[1].startswith("sqlite_")
)
cur.execute("DROP INDEX idx_age")
idx_after_drop = sorted(
r[1] for r in cur.execute("PRAGMA index_list(students)").fetchall() if not r[1].startswith("sqlite_")
)
drop_missing_err = False
try:
cur.execute("DROP INDEX idx_age")
except sqlite3.OperationalError:
drop_missing_err = True
case1 = make_case(
"create_and_drop_normal_index",
"Verify CREATE INDEX switches plan from SCAN to SEARCH USING INDEX and DROP INDEX removes it",
{
"before_uses_scan": True,
"after_uses_idx_name": True,
"idx_before_drop": ["idx_age", "idx_name"],
"idx_after_drop": ["idx_name"],
"drop_missing_err": True,
},
{
"before_uses_scan": "SCAN students" in plan_before,
"after_uses_idx_name": "USING INDEX idx_name" in plan_after,
"idx_before_drop": idx_before_drop,
"idx_after_drop": idx_after_drop,
"drop_missing_err": drop_missing_err,
},
)
# 2. UNIQUE index rejects duplicate values while allowing multiple NULLs
cur.execute("CREATE TABLE employees (id INT PRIMARY KEY, name TEXT, email TEXT)")
cur.execute("CREATE UNIQUE INDEX idx_email ON employees (email)")
cur.execute("INSERT INTO employees VALUES (1, 'Alice', 'alice@example.com')")
cur.execute("INSERT INTO employees VALUES (2, 'NoMail1', NULL)")
cur.execute("INSERT INTO employees VALUES (3, 'NoMail2', NULL)")
dup_email_blocked = False
try:
cur.execute("INSERT INTO employees VALUES (4, 'Clone', 'alice@example.com')")
except sqlite3.IntegrityError:
dup_email_blocked = True
null_email_count = cur.execute(
"SELECT COUNT(*) FROM employees WHERE email IS NULL"
).fetchone()[0]
case2 = make_case(
"create_unique_index_and_null_rule",
"Verify UNIQUE index blocks duplicate non-NULL emails while permitting multiple NULLs",
{
"dup_email_blocked": True,
"null_email_count": 2,
},
{
"dup_email_blocked": dup_email_blocked,
"null_email_count": null_email_count,
},
)
# 3. Composite index leftmost-prefix lookup vs non-leading column scan
cur.executescript(
"""
CREATE TABLE staff (
id INT PRIMARY KEY,
dept TEXT,
age INT
);
INSERT INTO staff VALUES
(1, 'Eng', 28), (2, 'Eng', 35), (3, 'Sales', 29), (4, 'HR', 31);
CREATE INDEX idx_dept_age ON staff (dept ASC, age DESC);
"""
)
plan_leading = cur.execute(
"EXPLAIN QUERY PLAN SELECT * FROM staff WHERE dept = 'Eng' AND age >= 30"
).fetchone()[3]
plan_non_leading = cur.execute(
"EXPLAIN QUERY PLAN SELECT * FROM staff WHERE age = 31"
).fetchone()[3]
case3 = make_case(
"composite_index_leftmost_prefix",
"Verify composite index (dept, age) serves leading-column predicate but falls back to SCAN on non-leading age",
{
"leading_uses_index": True,
"non_leading_scans_table": True,
},
{
"leading_uses_index": "USING INDEX idx_dept_age" in plan_leading,
"non_leading_scans_table": "SCAN staff" in plan_non_leading,
},
)
# 4. Index metadata inspection (SQLite PRAGMA index_list / index_info vs MySQL SHOW INDEX)
idx_meta = []
for row in cur.execute("PRAGMA index_list(employees)").fetchall():
name, unique = row[1], row[2]
if name.startswith("sqlite_"):
continue
cols = [c[2] for c in cur.execute(f"PRAGMA index_info({name})").fetchall()]
idx_meta.append({"name": name, "unique": bool(unique), "columns": cols})
case4 = make_case(
"index_metadata_inspection",
"Verify PRAGMA index_list/index_info exposes index name, uniqueness, and column list",
[{"name": "idx_email", "unique": True, "columns": ["email"]}],
idx_meta,
)
conn.close()
payload = {
"version": f"CPython {sys.version.split()[0]} / SQLite {sqlite3.sqlite_version} (offline MySQL verifier)",
"cases": [case1, case2, case3, case4],
}
print(json.dumps(payload, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 确认建索引后由 SCAN 转为 SEARCH USING INDEX、唯一索引拦截重复邮箱且允许多 NULL、组合索引最左前缀生效与 PRAGMA 索引元数据读取全部通过。
所需环境:Windows x64、CPython 3.12.14、内置 sqlite3(SQLite 3.53.1)本地离线关系语义验证环境(全程内存库或临时目录运行,未连接外部 MySQL 服务端)。
当前源码 SHA256:43507340b0853aa67c7f80ac9112204c50c891b230b68fb6d132676808793b9a
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、内置 sqlite3(SQLite 3.53.1)本地离线关系语义验证环境(全程内存库或临时目录运行,未连接外部 MySQL 服务端)。
ZIP SHA256:462ee112f7f9314459a8992cf8490a87e98ba0085553e07bf354f2590eccfaf3
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 `(dept, age)` 上建立了组合索引后,执行 `WHERE age = 31` 通常能否直接利用该组合索引的有序前缀查找?为什么?
展开参考解答
通常不能直接利用前导有序查找,因为 B+Tree 组合索引首先按 `dept` 排序、仅在 `dept` 相同的情况下才按 `age` 排序;跳过最左列 `dept` 直接按 `age` 过滤往往退化为全表扫描(或仅在覆盖索引下做全索引扫描)。