行百里er 行百里er
首页
  • 分类
  • 标签
  • 归档
设计模式
  • JVM
  • Java基础
MySQL
Elastic Stack
Redis
  • Kafka
  • RocketMQ
分布式
Spring Cloud Alibaba
云原生
数据结构与算法
关于
GitHub (opens new window)

行百里er

Java程序员一枚
首页
  • 分类
  • 标签
  • 归档
设计模式
  • JVM
  • Java基础
MySQL
Elastic Stack
Redis
  • Kafka
  • RocketMQ
分布式
Spring Cloud Alibaba
云原生
数据结构与算法
关于
GitHub (opens new window)
  • 如何在 CentOS 7 下快速安装 MySQL 5.7
  • 【调优向】捅破窗户纸-入门MySQL调优之性能监控
  • MySQL 数据类型也可以优化!
  • 【调优向】MySQL调优必备-执行计划explain与索引数据结构推演
  • 【MySQL调优向】用好你的MySQL索引,让效率飞起!
    • 哈希索引
      • 哈希索引的限制
      • 哈希索引使用案例
    • 组合索引
      • 组合索引使用案例
    • 聚簇索引与非聚簇索引
      • 聚簇索引
      • 非聚簇索引
    • 覆盖索引
      • 覆盖索引有哪些好处
      • 案例
    • 通过索引优化的一些细节
      • 1. 当使用索引列进行查询的时候尽量不要使用表达式,把计算放到业务层而不是数据库层
      • 2. 尽量使用主键查询,而不是其他索引,因为主键查询不会触发回表查询
      • 3. 使用前缀索引
      • 4. 使用索引扫描来排序
      • 5. union all,in,or都能够使用索引,但是推荐使用in
      • 6. 范围列可以用到索引
      • 7. 强制类型转换会全表扫描
      • 4. 更新十分频繁,数据区分度不高的字段上不宜建立索引
      • 5. 创建索引的列,不允许为null,可能会得到不符合预期的结果
      • 6. 当需要进行表连接的时候,最好不要超过三张表,因为需要join的字段,数据类型必须一致
      • 7. 能使用limit的时候尽量使用limit
      • 8. 单表索引建议控制在5个以内
      • 9. 组合索引的字段数不允许超过5个
      • 10. 创建索引的时候应该避免以下错误概念
    • 索引监控
    • 看两个索引优化的案例
  • 【调优向】关于 MySQL 查询的优化
  • 【MySQL系列】MySQL主从复制
  • 【MySQL系列】真香!基于ShardingSphere-JDBC的MySQL读写分离
  • 关于MySQL主从复制的数据同步延迟问题
  • 【MySQL8入门之安装篇】CentOS7系统下安装MySQL8
  • 【MySQL 8】MySQL 5.7都即将停只维护了,是时候学习一波MySQL 8了!
  • 重要数据不能丢!MySQL数据库定期备份保驾护航!
  • MySQL
行百里er
2020-08-17
目录

【MySQL调优向】用好你的MySQL索引,让效率飞起!

作者:行百里er

博客:https://chendapeng.cn (opens new window)

提示

这里是 行百里er 的博客:行百里者半九十,凡事善始善终,吾将上下而求索!

提到MySQL优化,很多人第一时间会想到建索引,没错,正确的使用索引确实能达到优化SQL的目的。

通过索引优化,具体该怎么做,有哪些知识细节?我们来探讨一下。

有兴趣的老铁,也可阅读前两篇:

【调优向】捅破窗户纸-入门MySQL调优之性能监控 (opens new window)

【调优向】MySQL调优必备-执行计划explain与索引数据结构推演 (opens new window)

如果能挥手就给我点个赞,我就更有动力了,感谢~

# 哈希索引

在MySQL中,只有memory的存储引擎显式支持哈希索引。

哈希索引是基于哈希表的实现,只有精确匹配索引所有列的查询才有效。

哈希索引自身只需存储对应的hash值,所以索引的结构十分紧凑,这让哈希索引查找的速度非常快。

# 哈希索引的限制

  • 哈希索引只包含哈希值和行指针,而不存储字段值,所以不能使用索引中的值来避免读取行
  • 哈希索引数据并不是按照索引值顺序存储的,所以无法进行排序
  • 哈希索引不支持部分列匹配查找,哈希索引是使用索引列的全部内容来计算哈希值
  • 它们仅用于使用=或<=>运算符的相等比较(但非常快)。 它们不用于比较运算符(例如<)来查找值的范围。
  • 访问哈希索引的数据非常快,除非有很多哈希冲突,当出现哈希冲突的时候,存储引擎必须遍历链表中的所有行指针,逐行进行比较,直到找到所有符合条件的行

哈希(Hash)一般叫做散列,意思就是把一堆任意长度的字符串、数字或者二进制输入通过一定的算法(非常多的哈希算法)生成固定长度的一个数字(字符串)。因为算法原因,不同的输入就会得到不同的哈希值。

哈希表(Hash Table)一般叫做散列表,就是通过把键值计算出Hash值后,通过Hash值映射到表里面的某个位置。那么同样的键值,下次访问或者修改都是同一个映射位置,不同的键值因为计算出Hash值不一样映射的位置也会不同。

因为哈希值是通过一定算法生成的,那么就有一定的可能出现不同的输入得到的Hash值是一样的,就算我们可以通过调整算法尽量减少这种情况,但是也不可完全避免。发生这种情况后,我们就会出现两个不同的键值被映射到同一个位置了,这就是哈希冲突。

  • 哈希冲突比较多的话,维护的代价也会很高

# 哈希索引使用案例

当需要存储大量的URL,并且根据URL进行搜索查找,如果使用B+树,存储的内容就会很大(比如URL超长的情况):

select id from url where url=''
1

也可以利用将url使用CRC32做哈希,可以使用以下查询方式:

select id fom url where url='' and url_crc=CRC32('')
1

此查询性能较高原因是使用体积很小的索引来完成查找

# 组合索引

当包含多个列作为索引,需要注意的是正确的顺序依赖于该索引的查询,同时需要考虑如何更好的满足排序和分组的需要。

假设有个表建了索引(a, b, c),那么不同SQL语句使用索引的情况如下:

查询条件 组合索引是否发挥作用
where a=3 是,只使用了a
where a=3 and b=5 是,使用了a,b
where a=3 and b=5 and c=6 是,使用了a,b,c
where a=3 and b=5 是,使用了a,b
==where b=3 or c=5== ==否==
where a=3 and c=6 是,只使用了a
where a=3 and b<10 and c=7 是,使用了a,b
where a=3 and b like '%xxoo%' and c=7 是,只是用了a

# 组合索引使用案例

建表:

create table staffs(
    id int primary key auto_increment,
    name varchar(24) not null default '' comment '姓名',
    age int not null default 0 comment '年龄',
    pos varchar(20) not null default '' comment '职位',
    add_time timestamp not null default current_timestamp comment '入职时间'
) charset utf8 comment '员工记录表';
1
2
3
4
5
6
7

建一个组合索引:

alter table staffs add index idx_nap(name, age, pos);
1
  • 使用name,age,pos三个字段做查询条件,并且顺序按照组合索引顺序:
mysql> explain select * from staffs where name='zhangsan' and age=18 and pos='programmer'\G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: staffs
   partitions: NULL
         type: ref
possible_keys: idx_nap
          key: idx_nap
      key_len: 140
          ref: const,const,const
         rows: 1
     filtered: 100.00
        Extra: NULL
1 row in set, 1 warning (0.01 sec)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

该查询用到了索引idx_nap,type为ref,并且ref为const,const,const。这种是最理想的条件。

  • 使用name,age,pos三个字段做查询条件,并且顺序按照组合索引顺序,但是age使用了范围查询:
mysql> explain select * from staffs where name='zhangsan' and age>18 and pos='programmer'\G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: staffs
   partitions: NULL
         type: range
possible_keys: idx_nap
          key: idx_nap
      key_len: 78
          ref: NULL
         rows: 1
     filtered: 100.00
        Extra: Using index condition
1 row in set, 1 warning (0.01 sec)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

该查询的也用到了索引idx_nap,但type为range,我们知道range的查询效率要低于ref的。原因是该查询只用到了name和age两个索引,组合索引的pos字段没有用上。

  • 查询条件只用到组合索引的后两个字段
mysql> explain select * from staffs where age=18 and pos='programmer'\G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: staffs
   partitions: NULL
         type: ALL
possible_keys: NULL
          key: NULL
      key_len: NULL
          ref: NULL
         rows: 1
     filtered: 100.00
        Extra: Using where
1 row in set, 1 warning (0.00 sec)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

这个type就是ALL了,这种情况索引是失效的,没有用到索引,效率是最低的。

# 聚簇索引与非聚簇索引

# 聚簇索引

不是单独的索引类型,而是一种数据存储方式,指的是数据行跟相邻的键值紧凑的存储在一起。

InnoDB的存储方式就是聚簇索引,索引和值放在同一个文件,.ibd文件。

聚簇索引的优点

  • 可以把相关数据保存在一起
  • 数据访问更快,因为索引和数据保存在同一个树中
  • 使用覆盖索引扫描的查询可以直接使用叶子节点中的主键值

聚簇索引的缺点

  • 聚簇数据最大限度地提高了IO密集型应用的性能,如果数据全部在内存,那么聚簇索引就没有什么优势
  • 插入速度严重依赖于插入顺序,按照主键的顺序插入是最快的方式
  • 更新聚簇索引列的代价很高,因为会强制将每个被更新的行移动到新的位置
  • 基于聚簇索引的表在插入新行,或者主键被更新导致需要移动行的时候,可能面临页分裂的问题
  • 聚簇索引可能导致全表扫描变慢,尤其是行比较稀疏,或者由于页分裂导致数据存储不连续的时候

# 非聚簇索引

数据文件和索引文件分开存放,MyIsam存储引擎就是如此。

# 覆盖索引

如果一个索引包含所有需要查询的字段的值,我们称之为覆盖索引,比如这个:

select name,age,pos from staffs where name='zhangsan' and age=18 and pos='programmer';
1

不是所有类型的索引都可以称为覆盖索引,覆盖索引必须要存储索引列的值。

不同的存储实现覆盖索引的方式不同,不是所有的引擎都支持覆盖索引,memory不支持覆盖索引。

# 覆盖索引有哪些好处

  • 索引条目通常远小于数据行大小,如果只需要读取索引,那么MySQL就会极大的减少数据访问量
  • 因为索引是按照列值顺序存储的,所以对于IO密集型的范围查询会比随机从磁盘读取每一行数据的IO要少的多
  • 一些存储引擎如MYISAM在内存中只缓存索引,数据则依赖于操作系统来缓存,因此要访问数据需要一次系统调用,这可能会导致严重的性能问题
  • 由于INNODB的聚簇索引,覆盖索引对INNODB表特别有用

# 案例

MySQL官网上很贴心的给出了一些示例,并且很贴心的建了一些表供我们使用,我们可以下载下来直接用!!!

比如MySQL提供的sakila数据库:

我们可以从这里获取:

下载下来之后我们导入本地进行测试:

mysql> source /root/soft/sakila-schema.sql
mysql> source /root/soft/sakila-data.sql
1
2

好了,可以愉快地使用这些表了。

  1. 当发起一个被索引覆盖的查询时,在explain的extra列可以看到using index的信息,此时就使用了覆盖索引
mysql> explain select store_id,film_id from inventory\G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: inventory
   partitions: NULL
         type: index
possible_keys: NULL
          key: idx_store_id_film_id
      key_len: 3
          ref: NULL
         rows: 4581
     filtered: 100.00
        Extra: Using index
1 row in set, 1 warning (0.00 sec)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  1. 在大多数存储引擎中,覆盖索引只能覆盖那些只访问索引中部分列的查询。不过,可以进一步的进行优化,可以使用innodb的二级索引来覆盖查询

例如actor表:

mysql> desc actor;
+-------------+----------------------+------+-----+-------------------+-----------------------------+
| Field       | Type                 | Null | Key | Default           | Extra                       |
+-------------+----------------------+------+-----+-------------------+-----------------------------+
| actor_id    | smallint(5) unsigned | NO   | PRI | NULL              | auto_increment              |
| first_name  | varchar(45)          | NO   |     | NULL              |                             |
| last_name   | varchar(45)          | NO   | MUL | NULL              |                             |
| last_update | timestamp            | NO   |     | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
+-------------+----------------------+------+-----+-------------------+-----------------------------+
4 rows in set (0.00 sec)
1
2
3
4
5
6
7
8
9
10

actor使用innodb存储引擎,并在last_name字段有二级索引,虽然该索引的列不包括主键actor_id,但也能够用于对actor_id做覆盖查询

mysql> explain select actor_id,last_name from actor where last_name='HOPPER'\G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: actor
   partitions: NULL
         type: ref
possible_keys: idx_actor_last_name
          key: idx_actor_last_name
      key_len: 182
          ref: const
         rows: 2
     filtered: 100.00
        Extra: Using index
1 row in set, 1 warning (0.00 sec)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# 通过索引优化的一些细节

# 1. 当使用索引列进行查询的时候尽量不要使用表达式,把计算放到业务层而不是数据库层

看一个案例:

mysql> select actor_id from actor where actor_id=4;
+----------+
| actor_id |
+----------+
|        4 |
+----------+
1 row in set (0.00 sec)

mysql> select actor_id from actor where actor_id+1=5;
+----------+
| actor_id |
+----------+
|        4 |
+----------+
1 row in set (0.02 sec)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

第一条语句和第二条语句查询结果是一样的,但是执行效率是有差别的:

mysql> explain select actor_id from actor where actor_id=4;
+----+-------------+-------+------------+-------+---------------+---------+---------+-------+------+----------+-------------+
| id | select_type | table | partitions | type  | possible_keys | key     | key_len | ref   | rows | filtered | Extra       |
+----+-------------+-------+------------+-------+---------------+---------+---------+-------+------+----------+-------------+
|  1 | SIMPLE      | actor | NULL       | const | PRIMARY       | PRIMARY | 2       | const |    1 |   100.00 | Using index |
+----+-------------+-------+------------+-------+---------------+---------+---------+-------+------+----------+-------------+
1 row in set, 1 warning (0.00 sec)

mysql> explain select actor_id from actor where actor_id+1=4;
+----+-------------+-------+------------+-------+---------------+---------------------+---------+------+------+----------+--------------------------+
| id | select_type | table | partitions | type  | possible_keys | key                 | key_len | ref  | rows | filtered | Extra                    |
+----+-------------+-------+------------+-------+---------------+---------------------+---------+------+------+----------+--------------------------+
|  1 | SIMPLE      | actor | NULL       | index | NULL          | idx_actor_last_name | 182     | NULL |  200 |   100.00 | Using where; Using index |
+----+-------------+-------+------------+-------+---------------+---------------------+---------+------+------+----------+--------------------------+
1 row in set, 1 warning (0.02 sec)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

第一个type是const效率高于第二条语句index。

# 2. 尽量使用主键查询,而不是其他索引,因为主键查询不会触发回表查询

# 3. 使用前缀索引

有时候需要索引很长的字符串,这会让索引变的大且慢,通常情况下可以使用某个列开始的部分字符串,这样大大的节约索引空间,从而提高索引效率。

但这会降低索引的选择性,索引的选择性是指不重复的索引值和数据表记录总数的比值,范围从1/#T到1之间。

索引的选择性越高则查询效率越高,因为选择性更高的索引可以让MySQL在查找的时候过滤掉更多的行。

一般情况下某个列前缀的选择性也是足够高的,足以满足查询的性能,但是对应BLOB,TEXT,VARCHAR类型的列,必须要使用前缀索引,因为MySQL不允许索引这些列的完整长度,使用该方法的诀窍在于要选择足够长的前缀以保证较高的选择性,通过又不能太长。

我们来构造一些数据表和数据:

mysql> create table citydemo(city varchar(50) not null);
Query OK, 0 rows affected (0.04 sec)

mysql> insert into citydemo(city) select city from city;
Query OK, 600 rows affected (0.03 sec)
Records: 600  Duplicates: 0  Warnings: 0

mysql> insert into citydemo(city) select city from citydemo;
Query OK, 600 rows affected (0.03 sec)
Records: 600  Duplicates: 0  Warnings: 0

mysql> insert into citydemo(city) select city from citydemo;
Query OK, 1200 rows affected (0.01 sec)
Records: 1200  Duplicates: 0  Warnings: 0

mysql> insert into citydemo(city) select city from citydemo;
Query OK, 2400 rows affected (0.05 sec)
Records: 2400  Duplicates: 0  Warnings: 0

mysql> insert into citydemo(city) select city from citydemo;
\Query OK, 4800 rows affected (0.09 sec)
Records: 4800  Duplicates: 0  Warnings: 0

mysql> insert into citydemo(city) select city from citydemo;
Query OK, 9600 rows affected (0.16 sec)
Records: 9600  Duplicates: 0  Warnings: 0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

如此,我们构造了一些重复数据。

查找最常见的城市列表:

mysql> select count(*) as cnt,city from citydemo group by city order by cnt desc limit 10;
+-----+------------------+
| cnt | city             |
+-----+------------------+
|  64 | London           |
|  32 | Omiya            |
|  32 | Pontianak        |
|  32 | Antofagasta      |
|  32 | Salala           |
|  32 | Batna            |
|  32 | Shubra al-Khayma |
|  32 | Brescia          |
|  32 | Sunnyvale        |
|  32 | Clarksville      |
+-----+------------------+
10 rows in set (0.04 sec)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

发现每个值都出现了32+次,我们来查找最频繁出现的城市前缀,先从3个前缀字母开始:

mysql> select count(*) as cnt,left(city,3) as pref from citydemo group by pref order by cnt desc limit 10;
+-----+------+
| cnt | pref |
+-----+------+
| 448 | San  |
| 192 | Cha  |
| 160 | Sal  |
| 160 | Tan  |
| 160 | Sou  |
| 160 | al-  |
| 128 | Hal  |
| 128 | Bat  |
| 128 | Man  |
| 128 | Sha  |
+-----+------+
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

可以看到用left(city,3)截取前三个作为前缀查询的结果和之前整列查找差别比较大,继续增加截取的字符数查询,这次用left(city, 5):

mysql> select count(*) as cnt,left(city,5) as pref from citydemo group by pref order by cnt desc limit 10;
+-----+-------+
| cnt | pref  |
+-----+-------+
| 128 | South |
|  96 | Santa |
|  64 | Chang |
|  64 | Toulo |
|  64 | Santi |
|  64 | Xiang |
|  64 | Valle |
|  64 | Londo |
|  64 | Saint |
|  64 | San F |
+-----+-------+
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

如你所见,差别变小了,以此法继续,最后确定left(city, 7)和最终的结果最接近:

mysql> select count(*) as cnt,left(city,7) as pref from citydemo group by pref order by cnt desc limit 10;
+-----+---------+
| cnt | pref    |
+-----+---------+
|  64 | Valle d |
|  64 | Santiag |
|  64 | London  |
|  64 | San Fel |
|  32 | Antofag |
|  32 | Batna   |
|  32 | Brescia |
|  32 | Clarksv |
|  32 | El Mont |
|  32 | Greensb |
+-----+---------+
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

也就是说,此时前缀的选择性接近于完整列的选择性。

前面说索引的选择性是指不重复的索引值和数据表记录总数的比值,那么计算完整列的选择性,还可以用如下方法:

select count(distinct left(city,3))/count(*) as sel3,
count(distinct left(city,4))/count(*) as sel4,
count(distinct left(city,5))/count(*) as sel5,
count(distinct left(city,6))/count(*) as sel6,
count(distinct left(city,7))/count(*) as sel7,
count(distinct left(city,8))/count(*) as sel8 
from citydemo;
1
2
3
4
5
6
7

结果:

至此,我们就可以愉快的建立前缀索引了:

alter table citydemo add key(city(7));
1

用一下瞅瞅:

type是ref级别的,效率还是很好的!

注意:前缀索引是一种能使索引更小更快的有效方法,但是也包含缺点:MySQL无法使用前缀索引做order by 和 group by。

# 4. 使用索引扫描来排序

MySQL有两种方式可以生成有序的结果:通过排序操作或者按索引顺序扫描,如果explain出来的type列的值为index,则说明MySQL使用了索引扫描来做排序。

扫描索引本身是很快的,因为只需要从一条索引记录移动到紧接着的下一条记录。但如果索引不能覆盖查询所需的全部列,那么就不得不每扫描一条索引记录就得回表查询一次对应的行,这基本都是随机IO,因此按索引顺序读取数据的速度通常要比顺序地全表扫描慢。

MySQL可以使用同一个索引即满足排序,又用于查找行,如果可能的话,设计索引时应该尽可能地同时满足这两种任务。

只有当索引的列顺序和order by子句的顺序完全一致,并且所有列的排序方式都一样时,MySQL才能够使用索引来对结果进行排序,如果查询需要关联多张表,则只有当order by子句引用的字段全部为第一张表时,才能使用索引做排序。order by子句和查找型查询的限制是一样的,需要满足索引的最左前缀的要求,否则,MySQL都需要执行顺序操作,而无法利用索引排序。

例:

sakila数据库中rental表在rental_date,inventory_id,customer_id上有名称为rental_date的组合索引:

eg.1

mysql> explain select rental_id,staff_id from rental where rental_date='2005-05-25' order by inventory_id,customer_id\G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: rental
   partitions: NULL
         type: ref
possible_keys: rental_date
          key: rental_date
      key_len: 5
          ref: const
         rows: 1
     filtered: 100.00
        Extra: Using index condition
1 row in set, 1 warning (0.03 sec)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

此处order by子句不满足索引的最左前缀的要求,也可以用于查询排序,这是因为查询的第一列rental_date='2005-05-25'被指定为一个常数。

eg. 2

mysql> explain select rental_id,staff_id from rental where rental_date='2005-05-25' order by inventory_id desc\G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: rental
   partitions: NULL
         type: ref
possible_keys: rental_date
          key: rental_date
      key_len: 5
          ref: const
         rows: 1
     filtered: 100.00
        Extra: Using where
1 row in set, 1 warning (0.03 sec)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

该查询为索引的第一列提供了常量条件,而使用第二列进行排序,将两个列组合在一起,就形成了索引的最左前缀(顺序为rental_date,inventory_id)

eg.3

mysql> explain select rental_id,staff_id from rental where rental_date>'2005-05-25' order by rental_date,inventory_id\G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: rental
   partitions: NULL
         type: ALL
possible_keys: rental_date
          key: NULL
      key_len: NULL
          ref: NULL
         rows: 16005
     filtered: 50.00
        Extra: Using where; Using filesort
1 row in set, 1 warning (0.00 sec)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

该查询第一列用的是范围查询,根据前面的铺垫,后面无论顺序如何,都不会按照索引进行排序了。从运行结果也能看到,该查询没有利用索引(Using filesort)。

eg. 4

mysql> explain select rental_id,staff_id from rental where rental_date='2005-05-25' order by inventory_id desc,customer_id asc\G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: rental
   partitions: NULL
         type: ref
possible_keys: rental_date
          key: rental_date
      key_len: 5
          ref: const
         rows: 1
     filtered: 100.00
        Extra: Using index condition; Using filesort
1 row in set, 1 warning (0.00 sec)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

该查询使用了两中不同的排序方向(先desc,后asc),但是索引列都是正序排序的,从结果看(Using filesort),也没有利用索引进行排序。

eg. 5

mysql> explain select rental_id,staff_id from rental where rental_date='2005-05-25' order by inventory_id desc,customer_id desc\G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: rental
   partitions: NULL
         type: ref
possible_keys: rental_date
          key: rental_date
      key_len: 5
          ref: const
         rows: 1
     filtered: 100.00
        Extra: Using where
1 row in set, 1 warning (0.00 sec)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

这个就用到了索引排序。

结合eg. 4,为什么按照两个方向(先desc,后asc)进行排序不利用索引,而同一方向就用了呢?

答:建立索引的时候默认是按照升序存储的,在B+树上,从上往下查找,如果都是desc,反过来从下往上查找即可。但是你同时整了两个方向的查找,B+树上,在一个节点里面还怎么对它进行排序,怎么直接读取索引里面的值?

# 5. union all,in,or都能够使用索引,但是推荐使用in

还是用sakila这个数据库的表

mysql> explain select * from actor where actor_id = 1 union all select * from actor where actor_id = 2;
+----+-------------+-------+------------+-------+---------------+---------+---------+-------+------+----------+-------+
| id | select_type | table | partitions | type  | possible_keys | key     | key_len | ref   | rows | filtered | Extra |
+----+-------------+-------+------------+-------+---------------+---------+---------+-------+------+----------+-------+
|  1 | PRIMARY     | actor | NULL       | const | PRIMARY       | PRIMARY | 2       | const |    1 |   100.00 | NULL  |
|  2 | UNION       | actor | NULL       | const | PRIMARY       | PRIMARY | 2       | const |    1 |   100.00 | NULL  |
+----+-------------+-------+------------+-------+---------------+---------+---------+-------+------+----------+-------+
2 rows in set, 1 warning (0.00 sec)

mysql> explain select * from actor where actor_id in (1,2);
+----+-------------+-------+------------+-------+---------------+---------+---------+------+------+----------+-------------+
| id | select_type | table | partitions | type  | possible_keys | key     | key_len | ref  | rows | filtered | Extra       |
+----+-------------+-------+------------+-------+---------------+---------+---------+------+------+----------+-------------+
|  1 | SIMPLE      | actor | NULL       | range | PRIMARY       | PRIMARY | 2       | NULL |    2 |   100.00 | Using where |
+----+-------------+-------+------------+-------+---------------+---------+---------+------+------+----------+-------------+
1 row in set, 1 warning (0.00 sec)

mysql>  explain select * from actor where actor_id = 1 or actor_id =2;
+----+-------------+-------+------------+-------+---------------+---------+---------+------+------+----------+-------------+
| id | select_type | table | partitions | type  | possible_keys | key     | key_len | ref  | rows | filtered | Extra       |
+----+-------------+-------+------------+-------+---------------+---------+---------+------+------+----------+-------------+
|  1 | SIMPLE      | actor | NULL       | range | PRIMARY       | PRIMARY | 2       | NULL |    2 |   100.00 | Using where |
+----+-------------+-------+------------+-------+---------------+---------+---------+------+------+----------+-------------+
1 row in set, 1 warning (0.00 sec)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

用执行计划分别测试一下union all、in和or,发现union all分两步执行,而in和or只用了一步,效率高一点。

但是用执行计划看不出in和or的差别,我们换做show profiles来看一下(先set profiling=1;):

mysql> show profiles;
+----------+------------+-------------------------------------------------------+
| Query_ID | Duration   | Query                                                 |
+----------+------------+-------------------------------------------------------+
|        1 | 0.00081575 | select * from actor where actor_id in (1,2)           |
|        2 | 0.02360075 | select * from actor where actor_id = 1 or actor_id =2 |
+----------+------------+-------------------------------------------------------+
2 rows in set, 1 warning (0.00 sec)
1
2
3
4
5
6
7
8

可以看到,用or的执行时间比in时间长。

因为使用or条件查询,会先判断一个条件进行筛选,再判断or中另外的条件再筛选,而in查询直接一次在in的集合里筛选。

所以,union all,in,or都能够使用索引,但是推荐使用in

# 6. 范围列可以用到索引

  • 范围条件是:<、<=、>、>=、between
  • 范围列可以用到索引,但是范围列后面的列无法用到索引,索引最多用于一个范围列

关于范围列使用索引以及索引生效规则,索引优化细节(一)有提到。

# 7. 强制类型转换会全表扫描

比如有这样一个表,phone列上建了索引,数据类型是varchar类型,存储的是手机号码:

create table user(id int,name varchar(10),phone varchar(11));

alter table user add index idx_1(phone);
1
2
3

用执行计划explain看一下,条件分别用where phone=13800001234和phone='13800001234':

可以看到,前者会触发全表扫描(type为ALL),后者用到了索引进行查询。

所以,这个细节提醒我们,在查询的时候虽然MySQL会帮助我们做一些数据类型的强制转换,但是如果有索引的话,索引也不会生效,因此,就老老实实的用定义的数据类型来查询吧。

# 4. 更新十分频繁,数据区分度不高的字段上不宜建立索引

数据更新操作会变更B+树,所以更新频繁的字段建立索引会大大降低数据库的性能。

比如类似于性别这类区分不大的属性,建立索引是没有意义的,不能有效的过滤数据。

一般区分度在80%以上的时候就可以建立索引,区分度可以使用 count(distinct(列名))/count(*) 来计算。

# 5. 创建索引的列,不允许为null,可能会得到不符合预期的结果

如果一个列上创建了索引,最好不要让它为null。但是具体情况具体分析,毕竟实际业务场景中很多字段是允许为null的。

# 6. 当需要进行表连接的时候,最好不要超过三张表,因为需要join的字段,数据类型必须一致

阿里规约里有这么一条:

【强制】超过三个表禁止 join 。需要 join 的字段,数据类型保持绝对一致 ; 多表关联查询时, 保证被关联的字段需要有索引。

说明:即使双表 join 也要注意表索引、SQL 性能。

被关联字段没有索引的话会大大降低MySQL的性能。

MySQL的join使用的是嵌套循环算法

  • Nested-Loop Join Algorithm

一种简单的嵌套循环联接(NLJ)算法,一次从一个循环中的第一个表中读取行,并将每行传递到一个嵌套循环中,该循环处理联接中的下一个表。重复此过程的次数与要连接的表的次数相同。

假定要使用以下联接类型执行三个表t1,t2和t3之间的联接:

Table   Join Type
t1      range
t2      ref
t3      ALL
1
2
3
4

那么,使用NLJ算法,join的执行过程像这样:

for each row in t1 matching range {
  for each row in t2 matching reference key {
    for each row in t3 {
      if row satisfies join conditions, send to client
    }
  }
}
1
2
3
4
5
6
7

因为NLJ算法一次将行从外循环传递到内循环,所以它通常会多次读取在内循环中处理的表。

  • Block Nested-Loop Join Algorithm

块嵌套循环(BNL)嵌套算法使用对在外部循环中读取的行的缓冲来减少必须读取内部循环中的表的次数。

例如,如果将10行读入缓冲区并将缓冲区传递到下一个内部循环,则可以将内部循环中读取的每一行与缓冲区中的所有10行进行比较。

这将内部表必须读取的次数减少了一个数量级。

for each row in t1 matching range {
  for each row in t2 matching reference key {
    store used columns from t1, t2 in join buffer
    if buffer is full {
      for each row in t3 {
        for each t1, t2 combination in join buffer {
          if row satisfies join conditions, send to client
        }
      }
      empty join buffer
    }
  }
}

if buffer is not empty {
  for each row in t3 {
    for each t1, t2 combination in join buffer {
      if row satisfies join conditions, send to client
    }
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

如果S是连接缓冲区中每个存储的t1,t2组合的大小,而C是缓冲区中组合的数量,则扫描表t3的次数:

(S * C)/join_buffer_size + 1

join_buffer_size可以看一下多大:

mysql> show variables like '%join_buffer%';
+------------------+--------+
| Variable_name    | Value  |
+------------------+--------+
| join_buffer_size | 262144 |
+------------------+--------+
1
2
3
4
5
6

默认情况下,join_buffer_size的大小为256K

# 7. 能使用limit的时候尽量使用limit

不要认为limit就是拿来做分页的哦,limit的含义是限制输出,分页只是它的一种基本应用。

对于一个查询,如果明确知道要取前x行,不使用limit的话,MySQL将会一行一行的将全部结果按顺序查找,最后返回结果,借助于limit如果找到了指定行数,将直接返回查询结果,效率会有提升。

# 8. 单表索引建议控制在5个以内

并不是索引越多越好,索引也是要占空间的!

# 9. 组合索引的字段数不允许超过5个

# 10. 创建索引的时候应该避免以下错误概念

  • 索引越多越好
  • 过早优化,在不了解系统的情况下进行优化

# 索引监控

索引使用状态:

mysql> show status like 'Handler_read%';
+-----------------------+-------+
| Variable_name         | Value |
+-----------------------+-------+
| Handler_read_first    | 0     |
| Handler_read_key      | 6     |
| Handler_read_last     | 0     |
| Handler_read_next     | 0     |
| Handler_read_prev     | 0     |
| Handler_read_rnd      | 0     |
| Handler_read_rnd_next | 1117  |
+-----------------------+-------+
7 rows in set (0.05 sec)
1
2
3
4
5
6
7
8
9
10
11
12
13

各个Variable的含义:

Handler_read_first 读取索引第一个条目的次数

Handler_read_key 通过index获取数据的次数

Handler_read_last 读取索引最后一个条目的次数

Handler_read_next 通过索引读取下一条数据的次数

Handler_read_prev 通过索引读取上一条数据的次数

Handler_read_rnd 从固定位置读取数据的次数

Handler_read_rnd_next 从数据节点读取下一条数据的次数

通常我们只关注一下Handler_read_key和Handler_read_rnd_next就行了。如果它们的值比较大,说明用到索引的次数比较多,索引利用率高;反之如果都是0或者数值很小,这个时候就该慌了,说明索引没有起到作用,该检查SQL语句了!

# 看两个索引优化的案例

准备表

SET FOREIGN_KEY_CHECKS=0;
DROP TABLE IF EXISTS `itdragon_order_list`;
CREATE TABLE `itdragon_order_list` (
  `id` bigint(11) NOT NULL AUTO_INCREMENT COMMENT '主键id,默认自增长',
  `transaction_id` varchar(150) DEFAULT NULL COMMENT '交易号',
  `gross` double DEFAULT NULL COMMENT '毛收入(RMB)',
  `net` double DEFAULT NULL COMMENT '净收入(RMB)',
  `stock_id` int(11) DEFAULT NULL COMMENT '发货仓库',
  `order_status` int(11) DEFAULT NULL COMMENT '订单状态',
  `descript` varchar(255) DEFAULT NULL COMMENT '客服备注',
  `finance_descript` varchar(255) DEFAULT NULL COMMENT '财务备注',
  `create_type` varchar(100) DEFAULT NULL COMMENT '创建类型',
  `order_level` int(11) DEFAULT NULL COMMENT '订单级别',
  `input_user` varchar(20) DEFAULT NULL COMMENT '录入人',
  `input_date` varchar(20) DEFAULT NULL COMMENT '录入时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10003 DEFAULT CHARSET=utf8;

INSERT INTO itdragon_order_list VALUES ('10000', '81X97310V32236260E', '6.6', '6.13', '1', '10', 'ok', 'ok', 'auto', '1', 'itdragon', '2017-08-28 17:01:49');
INSERT INTO itdragon_order_list VALUES ('10001', '61525478BB371361Q', '18.88', '18.79', '1', '10', 'ok', 'ok', 'auto', '1', 'itdragon', '2017-08-18 17:01:50');
INSERT INTO itdragon_order_list VALUES ('10002', '5RT64180WE555861V', '20.18', '20.17', '1', '10', 'ok', 'ok', 'auto', '1', 'itdragon', '2017-09-08 17:01:49');
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

案例一:

select * from itdragon_order_list where transaction_id = "81X97310V32236260E";

通过执行计划查看

mysql> explain select * from itdragon_order_list where transaction_id = "81X97310V32236260E";
+----+-------------+---------------------+------------+------+---------------+------+---------+------+------+----------+-------------+
| id | select_type | table               | partitions | type | possible_keys | key  | key_len | ref  | rows | filtered | Extra       |
+----+-------------+---------------------+------------+------+---------------+------+---------+------+------+----------+-------------+
|  1 | SIMPLE      | itdragon_order_list | NULL       | ALL  | NULL          | NULL | NULL    | NULL |    3 |    33.33 | Using where |
+----+-------------+---------------------+------------+------+---------------+------+---------+------+------+----------+-------------+
1
2
3
4
5
6

发现type=ALL,需要进行全表扫描。

优化1:为transaction_id创建唯一索引:

create unique index idx_order_transaID on itdragon_order_list (transaction_id);
1

再来看下执行计划:

mysql> explain select * from itdragon_order_list where transaction_id = "81X97310V32236260E";
+----+-------------+---------------------+------------+-------+--------------------+--------------------+---------+-------+------+----------+-------+
| id | select_type | table               | partitions | type  | possible_keys      | key                | key_len | ref   | rows | filtered | Extra |
+----+-------------+---------------------+------------+-------+--------------------+--------------------+---------+-------+------+----------+-------+
|  1 | SIMPLE      | itdragon_order_list | NULL       | const | idx_order_transaID | idx_order_transaID | 453     | const |    1 |   100.00 | NULL  |
+----+-------------+---------------------+------------+-------+--------------------+--------------------+---------+-------+------+----------+-------+
1
2
3
4
5
6

当创建索引之后,唯一索引对应的type是const,通过索引一次就可以找到结果,普通索引对应的type是ref,表示非唯一性索引扫描,找到值还要进行扫描,直到将索引文件扫描完为止,显而易见,const的性能要高于ref。

优化2:使用覆盖索引,查询的结果变成 select transaction_id,而不是select *,当extra出现using index,表示使用了覆盖索引

mysql> explain select transaction_id from itdragon_order_list where transaction_id = "81X97310V32236260E"\G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: itdragon_order_list
   partitions: NULL
         type: const
possible_keys: idx_order_transaID
          key: idx_order_transaID
      key_len: 453
          ref: const
         rows: 1
     filtered: 100.00
        Extra: Using index
1
2
3
4
5
6
7
8
9
10
11
12
13
14

案例二:

创建组合索引

create index idx_order_levelDate on itdragon_order_list (order_level,input_date);
1

执行

mysql> explain select * from itdragon_order_list order by order_level,input_date\G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: itdragon_order_list
   partitions: NULL
         type: ALL
possible_keys: NULL
          key: NULL
      key_len: NULL
          ref: NULL
         rows: 3
     filtered: 100.00
        Extra: Using filesort
1
2
3
4
5
6
7
8
9
10
11
12
13
14

type: ALL,Extra: Using filesort,说明创建索引之后跟没有创建索引一样,都是全表扫描,都是文件排序。

  • 可以使用force index强制指定索引
mysql> explain select * from itdragon_order_list force index(idx_order_levelDate) order by order_level,input_date\G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: itdragon_order_list
   partitions: NULL
         type: index
possible_keys: NULL
          key: idx_order_levelDate
      key_len: 68
          ref: NULL
         rows: 3
     filtered: 100.00
        Extra: NULL
1
2
3
4
5
6
7
8
9
10
11
12
13
14

这样,type就到了index级别,效率略有提升了。

  • 其实给订单排序意义不大,给订单级别添加索引意义也不大,因此可以先确定order_level的值,然后再给input_date排序
mysql> explain select * from itdragon_order_list where order_level=3 order by input_date\G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: itdragon_order_list
   partitions: NULL
         type: ref
possible_keys: idx_order_levelDate
          key: idx_order_levelDate
      key_len: 5
          ref: const
         rows: 1
     filtered: 100.00
        Extra: Using index condition
1
2
3
4
5
6
7
8
9
10
11
12
13
14

这样搞,type能到ref级别,效果更好!


首发公众号 行百里er ,欢迎老铁们关注阅读指正。

上次更新: 2022/10/04, 18:14:30
【调优向】MySQL调优必备-执行计划explain与索引数据结构推演
【调优向】关于 MySQL 查询的优化

← 【调优向】MySQL调优必备-执行计划explain与索引数据结构推演 【调优向】关于 MySQL 查询的优化→

最近更新
01
重要数据不能丢!MySQL数据库定期备份保驾护航!
05-22
02
分布式事务解决方案之 Seata(二):Seata AT 模式
09-09
03
Seata 番外篇:使用 docker-compose 部署 Seata Server(TC)及 K8S 部署 Seata 高可用
09-05
更多文章>
Theme by Vdoing | Copyright © 2020-2023 行百里er | MIT License | 豫ICP备2022020385号-1
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式