Examine the structure of the city table:
±------------±---------±-----±----±--------±---------------+
| Field | Type | Null | Key | Default | Extra |
±------------±---------±-----±----±--------±---------------+
| ID | int | NO | PRI | NULL | auto_increment |
| Name | char(35) | NO | | | |
| CountryCode | char(3) | NO | | | |
| District | char(20) | NO | | | |
| Population | int | NO | MUL | 0 | |
±------------±---------±-----±----±--------±---------------+
Now examine this statement and output with a placeholder
EXPLAIN SELECT Name, Population FROM City WHERE Population=100231\G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: city
partitions: NULL
type: ref
possible_keys: pop_idx
key: pop_idx
key_len:
ref: const
rows: 1
filtered: 100
Extra: NULL
What is the value of keylength?
A)1
B)6
C)2
D)100231
E)4
F)5
问题分析
- 表结构:
city表中Population字段为int类型,且NOT NULL(Null列为NO)。 - 查询语句:
EXPLAIN SELECT Name, Population FROM City WHERE Population=100231\G EXPLAIN输出:使用索引pop_idx(possible_keys和key均为pop_idx),type为ref,ref为const,表示通过常量值进行索引查找。- 需要确定
key_len(索引键长度)的值。
key_len 的含义
key_len在EXPLAIN输出中表示索引键使用的字节数,具体取决于索引列的数据类型和是否为NULL。- 对于
int类型:int在 MySQL 中固定占用 4 字节。- 如果列是
NOT NULL,索引键长度就是数据类型大小(4 字节),无需额外字节存储NULL标志。
- 本场景中:
- 索引
pop_idx基于Population列(查询条件仅涉及Population)。 Population是int NOT NULL,因此索引键长度应为 4 字节。
- 索引
错误选项分析
- A) 1:可能对应
TINYINT(1 字节),但Population是int。 - B) 6:可能源于字符串索引或复合索引的计算,但这里
Population是单列int索引。 - C) 2:可能对应
SMALLINT(2 字节),但Population是int。 - D) 100231:是查询中的值,与索引长度无关。
- F) 5:可能出现在
NULLable列(4 字节 + 1 字节NULL标志),但Population是NOT NULL。
正确答案
- E) 4:因为
Population是int NOT NULL,索引键长度为 4 字节。
验证
- 在 MySQL 中,
int类型固定 4 字节,NOT NULL列无额外开销。 EXPLAIN输出中ref: const和rows: 1进一步确认索引被完整使用(等值查询)。
结论:keylength 的值为 4(选项 E)。




