20

MySQL 的覆盖索引与回表

 4 years ago
source link: https://segmentfault.com/a/1190000021718016
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

两大类索引

使用的存储引擎:MySQL5.7 InnoDB

聚簇索引

* 如果表设置了主键,则主键就是聚簇索引
* 如果表没有主键,则会默认第一个NOT NULL,且唯一(UNIQUE)的列作为聚簇索引
* 以上都没有,则会默认创建一个隐藏的row_id作为聚簇索引

由此可见,使用聚簇索引查询会很快,因为可以直接定位到行记录。

普通索引

InnoDB的普通索引叶子节点存储的是主键(聚簇索引)的值,而MyISAM的普通索引存储的是记录指针。

示例

建表

mysql> create table user(
    -> id int(10) auto_increment,
    -> name varchar(30),
    -> age tinyint(4),
    -> primary key (id),
    -> index idx_age (age)
    -> )engine=innodb charset=utf8mb4;

id 字段是聚簇索引,age 字段是普通索引(二级索引)

填充数据

insert into user(name,age) values('张三',30);
insert into user(name,age) values('李四',20);
insert into user(name,age) values('王五',40);
insert into user(name,age) values('刘八',10);

mysql> select * from user;
+----+--------+------+
| id | name  | age |
+----+--------+------+
| 1 | 张三  |  30 |
| 2 | 李四  |  20 |
| 3 | 王五  |  40 |
| 4 | 刘八  |  10 |
+----+--------+------+

索引存储结构

id 是主键,所以是聚簇索引,其叶子节点存储的是对应行记录的数据

B3eEFjB.jpg!web

聚簇索引(ClusteredIndex)

age 是普通索引(二级索引),非聚簇索引,其叶子节点存储的是聚簇索引的的值

uieEny2.jpg!web

普通索引(secondaryIndex)

如:select * from user where id = 1;

2y6ru2a.jpg!web

聚簇索引查找过程

如果查询条件为普通索引(非聚簇索引),需要扫描两次B+树,第一次扫描通过普通索引定位到聚簇索引的值,然后第二次扫描通过聚簇索引的值定位到要查找的行记录数据。

1. 先通过普通索引 age=30 定位到主键值 id=1
2. 再通过聚集索引 id=1 定位到行记录数据

JRjyUzi.jpg!web

普通索引查找过程第一步

niMFbiq.jpg!web

普通索引查找过程第二步

回表查询

先通过普通索引的值定位聚簇索引值,再通过聚簇索引的值定位行记录数据,需要扫描两次索引B+树,它的性能较扫一遍索引树更低。

索引覆盖

例如:select id,age from user where age = 10;

如何实现覆盖索引

1、如实现:select id,age from user where age = 10;
explain分析:因为age是普通索引,使用到了age索引,通过一次扫描B+树即可查询到相应的结果,这样就实现了覆盖索引

zEfUVbu.png!web

explain分析:age是普通索引,但name列不在索引树上,所以通过age索引在查询到id和age的值后,需要进行回表再查询name的值。此时的Extra列的NULL表示进行了回表查询

byqAjqq.png!web

为了实现索引覆盖,需要建组合索引idx_age_name(age,name)

drop index idx_age on user;
create index idx_age_name on user(`age`,`name`);

explain分析:此时字段age和name是组合索引idx_age_name,查询的字段id、age、name的值刚刚都在索引树上,只需扫描一次组合索引B+树即可,这就是实现了索引覆盖,此时的Extra字段为Using index表示使用了索引覆盖。

AbQVfuq.png!web

哪些场景适合使用索引覆盖来优化SQL

全表count查询优化

mysql> create table user(
    -> id int(10) auto_increment,
    -> name varchar(30),
    -> age tinyint(4),
    -> primary key (id),
    -> )engine=innodb charset=utf8mb4;

例如:select count(age) from user;

aaiA3mE.png!web

使用索引覆盖优化:创建age字段索引

create index idx_age on user(age);

ZB3eQvU.png!web

列查询回表优化

前文在描述索引覆盖使用的例子就是

例如:select id,age,name from user where age = 10;

使用索引覆盖:建组合索引idx_age_name(age,name)即可

分页查询

因为name字段不是索引,所以在分页查询需要进行回表查询,此时Extra为Using filesort文件排序,查询性能低下。

QRFBv2b.png!web

使用索引覆盖:建组合索引idx_age_name(age,name)

uEbEfa7.png!web


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK