表格示例:
create table samples (id int NOT NULL AUTO_INCREMENT, a int, b int, PRIMARY KEY(id));
插入 2,483,308 条记录
测试查询
select * from samples where a = 3434 and b = 4389;
没有索引:
**Timing (as measured by the server):**
Execution time: 0:00:0.57075288
Table lock wait time: 0:00:0.00008100
在 (a) 上有索引:
CREATE INDEX a_index ON samples (a) USING BTREE;
**Timing (as measured by the server):**
Execution time: 0:00:0.00021302
Table lock wait time: 0:00:0.00008300
仅使用索引 (a, b):
CREATE INDEX ab_index ON samples (a, b) USING BTREE;
**Timing (as measured by the server):**
Execution time: 0:00:0.00019394
Table lock wait time: 0:00:0.00007600
带有 (a) 和 (a, b) 索引:
**Timing (as measured by the server):**
Execution time: 0:00:0.00022304
Table lock wait time: 0:00:0.00008300
删除索引,不再有任何索引:
**Timing (as measured by the server):**
Execution time: 0:00:0.57105565
Table lock wait time: 0:00:0.00008300
再次使用 (a) 仅索引:
Execution time: 0:00:0.00021866
Table lock wait time: 0:00:0.00008700
是的,只添加 (a) 索引会显着提高速度。
奇怪的是,解释表明在存在 (a) 和 (a, b) 索引的情况下,mySQL 出于某种原因仍然使用 (a) 索引。
explain select * from samples where a = 45 and b = 3456;
+----+-------------+---------+------+---------- --------+---------+---------+--------+------+------ --------+
|编号 |选择类型 |表|类型 |可能的键 |关键 | key_len |参考 |行 |额外 |
+----+-------------+---------+------+---------- --------+---------+---------+--------+------+------ --------+
| 1 |简单 |样品 |参考 | a_index,ab_index | a_index | 5 |常量 | 1 |使用位置 |
+----+-------------+---------+------+---------- --------+---------+---------+--------+------+------ --------+