覆盖索引是指索引的叶子节点已包含所有要查询的列,因此不需要访问表数据,能极大地提高性能。覆盖索引对InnoDB的聚簇索引表特别有用,因为可以避免InnoDB二级索引的二次查询。MySQL里只有B树索引能做覆盖索引,因为必须要存储索引列的值,而哈希索引、空间索引、全文索引不可以。
当发起一个覆盖索引的查询时,在explain的Extra列可以看到Using Index,下面看一个例子,在表users有一个多列索引(login_id,status),执行计划如下
[sql] view plain copy print?- root@test 01:30:35>explain select login_id,status from users\G
- *************************** 1. row ***************************
- id: 1
- select_type: SIMPLE
- table: users
- type: index
- possible_keys: NULL
- key: login_id
- key_len: 387
- ref: NULL
- rows: 5309293
- Extra: Using index 对于innoDB来说,还有一个好处,就是二级索引包含主键值,所以二级索引还可以利用这个消息覆盖索引,如下所示:
[sql] view plain copy print?- root@test 01:34:17>explain select login_id,status,id from users\G
- *************************** 1. row ***************************
- id: 1
- select_type: SIMPLE
- table: users
- type: index
- possible_keys: NULL
- key: login_id
- key_len: 387
- ref: NULL
- rows: 5309293
- Extra: Using index
从上面我们可以知道,虽然二级索引的定义没有包含主键,但依然可以使用覆盖索引。