点赞再看,养成习惯,微信搜一搜【一角钱小助手】关注更多原创技术文章。
本文 GitHub org_hejianhui/JavaStudy 已收录,有我的系列文章。
前言
前两篇说完了索引底层数据结构、性能优化原理的基本概念。本篇将讲讲具体实践。对于一个以数据为中心的应用,数据库的好坏直接影响到程序的性能,因此数据库性能至关重要。一般来说,要保证数据库的效率,要做好以下四个方面的工作:
- 数据库表设计
- SQL语句优化
- 数据库参数配置
- 恰当的硬件资源和操作系统
此外,使用适当的存储过程,也能提升性能。这个顺序也表现了四个方面对性能影响的大小。
数据库表设计
通俗地理解三个范式,对于数据库设计大有好处。在数据库设计当中,为了更好地应用三个范式,就必须通俗地理解三个范式。
第一范式:1NF - 确保原子性
是对属性的原子性约束,要求属性(列)具有原子性,不可再分解;(只要是关系型数据库都满足 1NF)
第二范式:2NF - 确保表中每列都和主键相关
是对记录的唯一性约束,要求记录有唯一标识,即实体的唯一性;
先满足1NF,然后每张表要有主键,并且确保每一列都和主键相关,而不是主键的一部分(主要针对联合主键)。换言之,一个表中只保存一种数据而不是多种数据。
错误示范:商品订单信息错误设计
![](https://upload-images.jianshu.io/upload_images/10170978-c71dcca2c8c8ecb9.png&originHeight=160&originWidth=683&size=61916&status=done&style=none&width=683?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
正确示范:商品订单信息正确设计
![](https://upload-images.jianshu.io/upload_images/10170978-6b76db4d638aa624.png&originHeight=573&originWidth=390&size=19666&status=done&style=none&width=390?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
第三范式:3NF - 确保每列都和主键直接相关,而不是间接相关
3NF 是对字段冗余性的约束,它要求字段没有冗余。
第三范式需要确保数据表中的每一列数据都和主键直接相关,而不能间接相关。不能传递依赖,如非主键列A依赖非主键列B,非主键列B依赖主键。
关键字段 -> 非关键字段x -> 非关键字段y
案例1:
比如在设计一个订单数据表的时候,可以将客户编号作为一个外键和订单表建立相应的关系。而不可以在订单表中添加关于客户其它信息(比如姓名、所属公司等)字段。如下这两个表所示的设计就是一个满足第三范式的数据库表。
![](https://upload-images.jianshu.io/upload_images/10170978-9d1a74f16ec59b4a.png&originHeight=357&originWidth=586&size=65988&status=done&style=none&width=586?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
案例2:
假定学生关系表为 Student
(学号、姓名、年龄、所在学院、学院地点、学院电话),关键字为单一关键字“学号”,因为存在如下决定关系:
(学号)-> (姓名、年龄、所在学院、学院地点、学院电话)
即存在非关键字段“学院地点”、“学院电话”对关键字段“学号”的传递函数依赖。
它也会存在数据冗余,更新异常、插入异常和删除异常的情况。正确应把学生关系表分为如下两个表:
- 学生:(学号、姓名、年龄、所在学院)
- 学院:(学院、地点、电话)
范式化优缺点
范式化的优点:
- 重复数据少,不冗余;
- 维护更新快;
- 范式化的表更小,可在内存中运行。
范式化的缺点:
查询的时候经常需要很多关联,增加查询的代价。也可能使一些索引策略失效,因为范式化将列放在不同的表中,而这些列在一个表中本可以属于同一个索引。
反范式化的优缺点
反范式化的优点:
- 避免关联,几乎所有数据可以在一张表中显示。
- 可以设计有效的索引。
反范式化的缺点:
冗余数据多,更小维护麻烦,删除数据时也容易丢失重要信息。
数据表设计的建议
没有冗余的数据库设计可以做到,但是,没有冗余的数据库未必是最好的数据库,有时为列提高运行效率,就必须降低范式标准,适当保留冗余数据。具体做法:在概念数据模型设计时遵守第三范式,降低范式标准的工作放到物理数据模型设计时考虑。降低范式就是增加字段,允许冗余。
另外,《阿里巴巴Java开发手册》,数据库的表设计允许适当冗余,以提升SQL查询的性能,避免表的关联查询。
适度冗余,减少join的关联
冗余更新频率不高,但是查询频率极高的字段。如订单中的商品名称、微博发帖中的用户昵称。
![](https://upload-images.jianshu.io/upload_images/10170978-0b401c6a6ba8800e.png&originHeight=266&originWidth=1846&size=165394&status=done&style=none&width=923?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
大字段垂直拆分
![](https://upload-images.jianshu.io/upload_images/10170978-749fb7b205779b55.png&originHeight=238&originWidth=1850&size=161212&status=done&style=none&width=925?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
如把博客列表中的内容拆分出去,访问列表的时候不读取博客内容,为纵深的逻辑关系。
大表水平拆分
举例说明:在一个论坛系统里,管理员经常会发一些帖子,这些帖子要求在每个分类列表里都要置顶。
- 设计方案一:在发帖表里增加一列用来标示是否是管理员发帖,这样在每个分类列表展示时就需要对发帖表查询两次,一次是置顶帖,一次是普通帖,然后将两次结果合并。如果发帖表内容较大时,查询置顶帖的性能开销会比较大。
- 设计方案二:将置顶帖存放在一个单独的置顶表里。因为置顶帖数量相比会很少,但访问频率很高,这样从发帖表里分拆开来,访问的性能开销会少很多。
合适的数据类型
如果数据量一样,但数据类型更小的话,数据存放同样的数据就会占用更少的空间,这样检索同样的数据所带来的IO 消耗自然会降低,性能也就很自然的得到提升。此外,MySQL 对不同类型的数据,处理方式也不一样,比如在运算或者排序操作中,越简单的数据类型操作性能越高,所以对于要频繁进行运算或者排序的字段尽量选择简单的数据类型。
![](https://upload-images.jianshu.io/upload_images/10170978-165004a008e796ba.png&originHeight=834&originWidth=1832&size=346748&status=done&style=none&width=916?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
SQL语句优化
SQL优化的一般步骤
- 通过
show status
命令了解各种SQL的执行频率; - 定位执行效率较低的SQL语句-(重点
select
); - 通过
explain
分析低效率的SQL; - 确定问题并采取相应的优化措施。
-- select语句分类
Select
Dml数据操作语言(insert update delete)
dtl 数据事物语言(commit rollback savepoint)
Ddl数据定义语言(create alter drop..)
Dcl(数据控制语言) grant revoke
-- Show status 常用命令
--查询本次会话
Show session status like 'com_%'; //show session status like 'Com_select'
--查询全局
Show global status like 'com_%';
-- 给某个用户授权
grant all privileges on *.* to 'abc'@'%';
--为什么这样授权 'abc' 表示用户名 '@' 表示host, 查看一下mysql->user表就知道了
--回收权限
revoke all on *.* from 'abc'@'%';
--刷新权限[也可以不写]
flush privileges;
SQL语句优化-show参数
MySQL客户端连接成功后,通过使用 show [session|global] status
命令可以提供服务器状态信息。其中的session
来表示当前的连接的统计结果,global
来表示自数据库上次启动至今的统计结果。默认是session级别的。
show status like 'Com_%';
其中, Com_XXX
表示 XXX
语句所执行的次数。
重点注意:Com_select
,Com_insert
,Com_update
,Com_delete
通过这几个参数,可以了解到当前数据库的应用是以插入更新为主还是以查询操作为主,以及各类的SQL大致的执行比例是多少。
还有几个常用的参数便于用户了解数据库的基本情况。
Connections
:试图连接MySQL服务器的次数
Uptime
:服务器工作的时间(单位秒)
Slow_queries
:慢查询的次数 (默认是慢查询时间10s)
show status like 'Connections';
show status like 'Uptime';
show status like 'Slow_queries';
查询MySQL的慢查询时间
show variables like 'long_query_time';
修改MySQL慢查询时间
set long_query_time=2;
SQL语句优化-定位慢查询
上面我们介绍了获取MySQL数据库的一些运行状态是如何查询
- 比如当前MySQL运行的时间:
show status like 'Uptime';
- 一共执行了多少次
select/update/delete.. /
:show status like 'Com_%';
- 当前连接数
定位慢查询
如何从一个项目中快速定位执行速度慢的语句(定位慢查询)
show variables like '%query%';
![](https://upload-images.jianshu.io/upload_images/10170978-2fd3d140e253ddc6.png&originHeight=273&originWidth=544&size=71160&status=done&style=stroke&width=544?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
-
slow_query_log
默认是off关闭的,使用时,需要改为on 打开 -
slow_query_log_file
记录的是慢日志的记录文件 -
long_query_time
默认是10S,每次执行的sql达到这个时长,就会被记录
查看慢查询状态
Slow_queries 记录的是慢查询数量 当有一条sql执行一次比较慢时,这个vlue就是1 (记录的是本次会话的慢sql条数)
show status like '%slow_queries%';
![](https://upload-images.jianshu.io/upload_images/10170978-a559cb03fdebff9f.png&originHeight=52&originWidth=301&size=6540&status=done&style=stroke&width=301?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
注意:
- 如何打开慢查询 : SET GLOBAL slow_query_log = ON;
- 将默认时间改为1S: SET GLOBAL long_query_time = 1;
(设置完需要重新连接数据库,PS:仅在这里改的话,当再次重启数据库服务时,所有设置又会自动恢复成默认值,永久改变需去my.ini中改)
SQL语句优化-Explain工具
使用EXPLAIN
关键字可以模拟优化器执行SQL语句,分析你的查询语句或是结构的性能瓶颈 在 select 语句之前增加 explain 关键字,MySQL 会在查询上设置一个标记,执行查询会返回执行计划的信息,而不是执行这条SQL。
注意:如果 from 中包含子查询,仍会执行该子查询,将结果放入临时表中
Explain分析示例
DROP TABLE IF EXISTS `actor`;
CREATE TABLE `actor` (
`id` int(11) NOT NULL,
`name` varchar(45) DEFAULT NULL, `update_time` datetime DEFAULT NULL, PRIMARY KEY (`id`)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `actor` (`id`,`name`,`update_time`) VALUES (1,'a','2020-09-16 14:26:11'), (2,'b','2020-09-16 14:26:11'), (3,'c','2020-09-16 14:26:11');
DROP TABLE IF EXISTS` film`;
CREATE TABLE`film`(
`id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(10) DEFAULT NULL, PRIMARY KEY (`id`),
KEY `idx_name` (`name`)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `film`(`id`,`name`) VALUES (3,'film0'),(1,'film1'),(2,'film2');
DROP TABLE IF EXISTS `film_actor`;
CREATE TABLE`film_actor`(
`id` int(11) NOT NULL,
`film_id` int(11) NOT NULL,
`actor_id` int(11) NOT NULL,
`remark` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `idx_film_actor_id` (`film_id`,`actor_id`)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO`film_actor`(`id`,`film_id`,`actor_id`)VALUES(1,1,1), (2,1,2),(3,2,1);
explain select * from actor;
![](https://upload-images.jianshu.io/upload_images/10170978-47ebd03e0d843ec6.png&originHeight=48&originWidth=706&size=19515&status=done&style=stroke&width=706?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
查询中的每个表会输出一行,如果有两个表通过
join
连接查询,那么会输出两行。每一列具体的说明在后面进行说明。
Explain 两个变种
explain extended
会在 explain 的基础上额外提供一些查询优化的信息。紧随其后通过 show warnings 命令可以得到优化后的查询语句,从而看出优化器优化了什么。额外还有 filtered 列,是一个半分比的值,rows * filtered/100 可以估算出将要和 explain 中前一个表进行连接的行数(前一个表指 explain 中的id值比当前表id值小的表)。
explain extended select * from film where id = 1;
![](https://upload-images.jianshu.io/upload_images/10170978-390e32cfb529a3c9.png&originHeight=50&originWidth=803&size=27209&status=done&style=stroke&width=803?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
show warnings;
![](https://upload-images.jianshu.io/upload_images/10170978-8e6a72e3cc2be614.png&originHeight=71&originWidth=669&size=21311&status=done&style=stroke&width=669?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
explain partitions
相比 explain 多了个 partitions 字段,如果查询是基于分区表的话,会显示查询将访问的分区。
Explain中的列
接下来我们将展示 explain 中每个列的信息。
id 列
id 列的编号是 select 的序列号,有几个 select 就有几个 id,并且id的顺序是按 select 出现的顺序递增的。id列越大执行优先级越高,id相同则从上往下执行,id为 NULL 最后执行。
select_type 列
select_type
表示对应行是简单还是复杂的查询。
-
simple
:简单查询。查询不包含子查询和union
explain select * from film where id = 2;
![](https://upload-images.jianshu.io/upload_images/10170978-285e222e9b6672ae.png&originHeight=53&originWidth=813&size=27465&status=done&style=stroke&width=813?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
-
primary
:复杂查询中最外层的 select -
subquery
:包含在 select 中的子查询(不在 from 子句中) -
derived
:包含在 from 子句中的子查询。MySQL 会将结果存放在一个临时表中,也称为派生表(derived的英文含义)
用下面这个例子来了解 primary、subquery、derived类型。
explain select (select 1 from actor where id = 1) from (select * from film where id = 1) der;
未关闭MySQL5.7新特性对衍生表的合并优化,如下:
![](https://upload-images.jianshu.io/upload_images/10170978-c7dd9de920e19c24.png&originHeight=76&originWidth=858&size=37781&status=done&style=stroke&width=858?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
#关闭mysql5.7新特性对衍 生表的合并优化
set session optimizer_switch='derived_merge=off';
![](https://upload-images.jianshu.io/upload_images/10170978-18756c2714ffb0e8.png&originHeight=89&originWidth=834&size=47950&status=done&style=stroke&width=834?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
#还原默认配置
set session optimizer_switch='derived_merge=on';
-
union
:在 union 中的第二个和随后的 select
explain select 1 union all select 1;
![](https://upload-images.jianshu.io/upload_images/10170978-a2ebff64ab6787c2.png&originHeight=67&originWidth=855&size=40885&status=done&style=stroke&width=855?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
table 列
这一列表示 explain 的一行正在访问哪个表。
当 from 子句中有子查询时,table列是 格式,表示当前查询依赖 id=N 的查 询,于是先执行 id=N 的查询。
当有 union 时,UNION RESULT 的 table 列的值为<union1,2>,1和2表示参与 union 的 select 行id。
type 列
这一列表示关联类型或访问类型,即MySQL决定如何查找表中的行,查找数据行记录的大概范围。
依次从最优到最差分别为:
system > const > eq_ref > ref > range > index > ALL
一般来说,得保证查询达到 range
级别,最好达到 ref
。
NULL:MySQL 能够在优化阶段分解查询语句,在执行阶段用不着再访问表或索引。例如:在索引列中选取最小值,可以单独查找索引来完成,不需要在执行时访问表。
explain select min(id) from film;
![](https://upload-images.jianshu.io/upload_images/10170978-c12a9fc763b8ecd7.png&originHeight=61&originWidth=862&size=34888&status=done&style=stroke&width=862?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
system、const :MySQL 能对查询的某部分进行优化并将其转化成一个常量(可以看 show warnings 的)。用于 primary key
或 unique key
的所有列与常数比较时,所以表最多有一个匹配行,读取1次,速度比较快。system 是 const 的特例,表里只有一条元组匹配时为 system。
explain extended select * from (select * from film where id = 1) tmp;
![](https://upload-images.jianshu.io/upload_images/10170978-a7b033cdffe69689.png&originHeight=69&originWidth=801&size=34918&status=done&style=stroke&width=801?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
show warnings;
![](https://upload-images.jianshu.io/upload_images/10170978-810ec06485ca3818.png&originHeight=67&originWidth=643&size=25404&status=done&style=stroke&width=643?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
eq_ref :primary key 或 unique key 索引的所有部分被连接使用,最多只会返回一条符合条件的记录。这可能实在 const 之外最好的连接类型了,简单的 select 查询不会出现这种 type。
explain select * from film_actor left join film on film_actor.film_id = film.id;
![](https://upload-images.jianshu.io/upload_images/10170978-eadb8628119783e5.png&originHeight=77&originWidth=918&size=36750&status=done&style=stroke&width=918?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
ref :相比 eq_ref ,不使用唯一索引,而是使用普通索引或者唯一性索引的部分前缀,索引要和某个值相比较,可能会找到多个符合条件的行。
(1)简单 select 查询,name 是普通索引(非唯一索引)
explain select * from film where name = 'film1';
![](https://upload-images.jianshu.io/upload_images/10170978-4e3579498352a763.png&originHeight=57&originWidth=948&size=28100&status=done&style=stroke&width=948?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
(2)关联表查询,
idx_film_actor_id
是 film_id 和 actor_id 的联合索引,这里使用到了 film_actor 的左边前缀 film_id 部分。
explain select film_id from film left join film_actor on film.id = film_actor.film_id;
![](https://upload-images.jianshu.io/upload_images/10170978-c9016ab88ebae5e6.png&originHeight=71&originWidth=990&size=40270&status=done&style=stroke&width=990?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
range : 范围扫描通常出现在 in()、betwwen、>、<、>=
等操作中。使用一个索引来检索给定范围的行。
explain select * from actor where id > 1;
![](https://upload-images.jianshu.io/upload_images/10170978-308b4633c70fd2bc.png&originHeight=54&originWidth=993&size=28279&status=done&style=stroke&width=993?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
index :扫描全表索引,通过比 ALL 快一些。
explain select * from film;
![](https://upload-images.jianshu.io/upload_images/10170978-43609b6d81de5fe0.png&originHeight=56&originWidth=989&size=28166&status=done&style=stroke&width=989?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
ALL :即全表扫描,意味着MySQL需要从头到尾去查找所需要的行。通常情况下这需要增加索引来进行优化了。
explain select * from actor
![](https://upload-images.jianshu.io/upload_images/10170978-1116d1d2222999f5.png&originHeight=54&originWidth=985&size=23504&status=done&style=stroke&width=985?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
possible_keys 列
这一列显示查询可能使用哪些索引来查找。
explain 时可能出现 possible_keys 有列,而 key 显示 NULL 的情况,这种情况是因为表中数据不多,mysql认为索引对此查询帮助不大,选择了全表查询。 如果该列是NULL,则没有相关的索引。在这种情况下,可以通过检查 where 子句看是否可以创造一个适当的索引来提高查询性能,然后用 explain 查看效果。
key 列
这一列显示mysql实际采用哪个索引来优化对该表的访问。
如果没有使用索引,则该列是 NULL。如果想强制mysql使用或忽视possible_keys列中的索 引,在查询中使用 force index
、ignore index
。
key_len 列
这一列显示了mysql在索引里使用的字节数,通过这个值可以算出具体使用了索引中的哪些 列。
举例来说,film_actor的联合索引 idx_film_actor_id 由 film_id 和 actor_id 两个int列组成, 并且每个int是4字节。通过结果中的key_len=4可推断出查询使用了第一个列:film_id列来执 行索引查找。
explain select * from film_actor where film_id = 2;
![](https://upload-images.jianshu.io/upload_images/10170978-0642e42f1d42cc10.png&originHeight=56&originWidth=987&size=30050&status=done&style=stroke&width=987?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
key_len计算规则如下:
字符串
- char(n):n字节长度
- varchar(n):2字节存储字符串长度,如果是utf-8,则长度 3n +2
数值类型
- tinyint:1字节
- smallint:2字节
- int:4字节
- bigint:8字节
时间类型
- date:3字节
- timestamp:4字节
- datetime:8字节
如果字段允许为 NULL,需要1字节记录是否为 NULL
索引最大长度是768字节,当字符串过长时,mysql会做一个类似左前缀索引的处理,将前半部分的字符提取出来做索引。
ref 列
这一列显示了在key列记录的索引中,表查找值所用到的列或常量,常见的有:const(常 量),字段名(例:film.id)
rows 列
这一列是mysql估计要读取并检测的行数,注意这个不是结果集里的行数。
Extra 列
这一列展示的是额外信息。常见的重要值如下:
(1)Using index:使用覆盖索引
explain select film_id from film_actor where film_id = 1;
![](https://upload-images.jianshu.io/upload_images/10170978-4d59bb3b6bc65c92.png&originHeight=52&originWidth=990&size=31782&status=done&style=stroke&width=990?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
(2)Using where :使用 where 语句来处理结果,查询的列未被索引覆盖
explain select * from actor where name = 'a';
![](https://upload-images.jianshu.io/upload_images/10170978-1f9b89ef8df91bcc.png&originHeight=55&originWidth=992&size=27075&status=done&style=stroke&width=992?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
(3)Using index condition :查询的列不完全被索引覆盖,where 条件中是一个前导列的范围
explain select * from film_actor where film_id > 1;
![](https://upload-images.jianshu.io/upload_images/10170978-27bfda2f4792be18.png&originHeight=56&originWidth=1018&size=31319&status=done&style=stroke&width=1018?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
(4)Using temporary :MySQL 需要创建一张临时表来处理查询。出现这种情况一般是要进行优化的,首先是想到用索引来优化。
- actor.name没有索引,此时创建了张临时表来distinct
explain select distinct name from actor;
![](https://upload-images.jianshu.io/upload_images/10170978-812b6f205f0b214e.png&originHeight=53&originWidth=1019&size=26840&status=done&style=stroke&width=1019?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
- film.name建立了idx_name索引,此时查询时extra是using index,没有用临时表
explain select distinct name from film;
![](https://upload-images.jianshu.io/upload_images/10170978-e42c9ad7c93c4c44.png&originHeight=59&originWidth=1015&size=27739&status=done&style=stroke&width=1015?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
(5)Using filesort : 将用外部排序而不是索引排序,数据较小时从内存排序,否则需要在磁盘 完成排序。这种情况下一般也是要考虑使用索引来优化的。
- actor.name没有索引,会浏览 actor 整个表,保存排序关键字 name 和对应的 id,然后排序 name 并检索行记录。
explain select * from actor order by name;
![](https://upload-images.jianshu.io/upload_images/10170978-ecd5fcb16518fe92.png&originHeight=53&originWidth=1021&size=28079&status=done&style=stroke&width=1021?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
- film.name建立了idx_name索引,此时查询时extra是using index
explain select * from film order by name;
![](https://upload-images.jianshu.io/upload_images/10170978-e78d3673b4e60f37.png&originHeight=51&originWidth=1014&size=27426&status=done&style=stroke&width=1014?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
(6)Select tables optimized away :使用某些聚合函数(比如 max、min)来访问存在索引 的某个字段是
explain select min(id) from film;
![](https://upload-images.jianshu.io/upload_images/10170978-37c88c17d57c692d.png&originHeight=53&originWidth=1057&size=31051&status=done&style=stroke&width=1057?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
SQL语句优化-索引最佳实践
# 示例表
CREATE TABLE`employees`(
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(24) NOT NULL DEFAULT '' COMMENT '姓名',
`age` int(11) NOT NULL DEFAULT '0' COMMENT '年龄',
`position` varchar(20) NOT NULL DEFAULT '' COMMENT '职位',
`hire_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '入职时间',
PRIMARY KEY (`id`),
KEY `idx_name_age_position` (`name`,`age`,`position`) USING BTREE
)ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COMMENT='员工记录表';
INSERT INTO employees(name,age,position,hire_time)VALUES('ZhangSan',23,'Manager',NOW());
INSERT INTO employees(name,age,position,hire_time)VALUES('HanMeimei', 23,'dev',NOW());
INSERT INTO employees(name,age,position,hire_time) VALUES('Lucy',23,'dev',NOW());
全值匹配
EXPLAIN SELECT * FROM employees WHERE name= 'ZhangSan';
![](https://upload-images.jianshu.io/upload_images/10170978-a9f2eac036931fa1.png&originHeight=61&originWidth=962&size=36871&status=done&style=stroke&width=962?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
EXPLAIN SELECT * FROM employees WHERE name= 'ZhangSan' AND age = 22;
![](https://upload-images.jianshu.io/upload_images/10170978-5201b210a3a34a58.png&originHeight=55&originWidth=974&size=38357&status=done&style=stroke&width=974?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
EXPLAIN SELECT * FROM employees WHERE name= 'ZhangSan' AND age = 22 AND position ='manager';
![](https://upload-images.jianshu.io/upload_images/10170978-04d1ed18492fbd52.png&originHeight=56&originWidth=993&size=36248&status=done&style=stroke&width=993?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
最左前缀法则
如果索引了多列,要遵守最左前缀法则。指的是查询从索引的最左前列开始并且不跳过索引中的列。
EXPLAIN SELECT * FROM employees WHERE age = 22 AND position ='manager';
![](https://upload-images.jianshu.io/upload_images/10170978-b41ee3b0d32704e1.png&originHeight=54&originWidth=1053&size=31407&status=done&style=stroke&width=1053?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
EXPLAIN SELECT * FROM employees WHERE position = 'manager';
![](https://upload-images.jianshu.io/upload_images/10170978-8d60f88641024691.png&originHeight=51&originWidth=1036&size=30121&status=done&style=stroke&width=1036?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
EXPLAIN SELECT * FROM employees WHERE name = 'ZhangSan';
![](https://upload-images.jianshu.io/upload_images/10170978-5c1ba3fcbc34aad2.png&originHeight=51&originWidth=1012&size=32701&status=done&style=stroke&width=1012?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
不在索引列上做任何操作
不在索引列上做任何操作(计算、函数、(自动or手动)类型转换),会导致索引失效而转向全表扫描。
EXPLAIN SELECT * FROM employees WHERE name = 'ZhangSan';
EXPLAIN SELECT * FROM employees WHERE left(name,3) = 'ZhangSan';
![](https://upload-images.jianshu.io/upload_images/10170978-c79ffb4c93eb356a.png&originHeight=60&originWidth=1009&size=28700&status=done&style=stroke&width=1009?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
给hire_time增加一个普通索引:
ALTER TABLE `employees`
ADD INDEX `idx_hire_time` (`hire_time`) USING BTREE;
EXPLAIN select * from employees where date(hire_time) ='2020-09-30';
![](https://upload-images.jianshu.io/upload_images/10170978-895f0d5b32fb53e6.png&originHeight=56&originWidth=1013&size=31284&status=done&style=stroke&width=1013?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
转化为日期范围查询,会走索引:
EXPLAIN select * from employees where hire_time >='2020-09-30 00:00:00' and hire_time <='2020-09-30 23:59:59';
![](https://upload-images.jianshu.io/upload_images/10170978-a20999d2784c861c.png&originHeight=58&originWidth=1072&size=33748&status=done&style=stroke&width=1072?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
还原最初索引状态
ALTER TABLE `employees`
DROP INDEX `idx_hire_time`;
存储引擎不能使用索引中范围条件右边的列
EXPLAIN SELECT * FROM employees WHERE name= 'ZhangSan' AND age = 22 AND position ='manager';
EXPLAIN SELECT * FROM employees WHERE name= 'ZhangSan' AND age > 22 AND position ='manager';
![](https://upload-images.jianshu.io/upload_images/10170978-465818c232df7979.png&originHeight=52&originWidth=1069&size=34621&status=done&style=stroke&width=1069?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
尽量使用覆盖索引
尽量使用覆盖索引(只访问索引的查询(索引列包含查询列)),减少select *
语句。
EXPLAIN SELECT name,age FROM employees WHERE name= 'ZhangSan' AND age = 23 AND position ='manager';
![](https://upload-images.jianshu.io/upload_images/10170978-063bafa1cf2ed23f.png&originHeight=61&originWidth=1090&size=32762&status=done&style=stroke&width=1090?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
EXPLAIN SELECT * FROM employees WHERE name= 'ZhangSan' AND age = 23 AND position ='manager';
![](https://upload-images.jianshu.io/upload_images/10170978-0a9b22b8237a07f3.png&originHeight=52&originWidth=1071&size=33163&status=done&style=stroke&width=1071?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
mysql在使用不等于(!=或者<>)的时候无法使用索引会导致全表扫描
EXPLAIN SELECT * FROM employees WHERE name != 'ZhangSan';
![](https://upload-images.jianshu.io/upload_images/10170978-f82bd779097322be.png&originHeight=62&originWidth=1109&size=39825&status=done&style=stroke&width=1109?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
is null、is not null
也无法使用索引
EXPLAIN SELECT * FROM employees WHERE name is null
![](https://upload-images.jianshu.io/upload_images/10170978-e11858d8c793416e.png&originHeight=59&originWidth=1152&size=31975&status=done&style=stroke&width=1152?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
like以通配符开头('%abc...')mysql索引失效会变成全表扫描操作
EXPLAIN SELECT * FROM employees WHERE name like '%Zhang'
![](https://upload-images.jianshu.io/upload_images/10170978-4f3452b14e9a3a19.png&originHeight=52&originWidth=1123&size=30803&status=done&style=stroke&width=1123?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
EXPLAIN SELECT * FROM employees WHERE name like 'Zhang%'
![](https://upload-images.jianshu.io/upload_images/10170978-04a32b6825a0dc1a.png&originHeight=55&originWidth=1153&size=35737&status=done&style=stroke&width=1153?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
问题:解决like'%字符串%'索引不被使用的方法?
- 使用覆盖索引,查询字段必须是建立覆盖索引字段
EXPLAIN SELECT name,age,position FROM employees WHERE name like '%Zhang%';
![](https://upload-images.jianshu.io/upload_images/10170978-d49c7f864ad91a05.png&originHeight=58&originWidth=1145&size=35506&status=done&style=stroke&width=1145?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
- 如果不能使用覆盖索引则可能需要借助搜索引擎
字符串不加单引号索引失效
EXPLAIN SELECT * FROM employees WHERE name = '1000';
EXPLAIN SELECT * FROM employees WHERE name = 1000;
![](https://upload-images.jianshu.io/upload_images/10170978-70b07206fe5ccb96.png&originHeight=57&originWidth=1131&size=34344&status=done&style=stroke&width=1131?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
少用or或in
少用or或in,用它查询时,mysql不一定使用索引,mysql内部优化器会根据检索比例、 表大小等多个因素整体评估是否使用索引,详见范围查询优化。
EXPLAIN SELECT * FROM employees WHERE name = 'ZhangSan' or name = 'HanMeimei';
![](https://upload-images.jianshu.io/upload_images/10170978-bdfee5bd48fc5b32.png&originHeight=55&originWidth=1079&size=32150&status=done&style=stroke&width=1079?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
范围查询优化
给年龄添加单值索引
ALTER TABLE`employees`
ADD INDEX `idx_age` (`age`)USING BTREE;
explain select * from employees where age >=1 and age <=2000;
![](https://upload-images.jianshu.io/upload_images/10170978-ab8ea34369c48473.png&originHeight=54&originWidth=1099&size=30685&status=done&style=stroke&width=1099?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
没走索引原因:mysql内部优化器会根据检索比例、表大小等多个因素整体评估是否使用索引。比如这个例子,可能是由于单次数据量查询过大导致优化器最终选择不走索引 优化方法:可以讲大的范围拆分成多个小范围。
explain select * from employees where age >=1 and age <=1000;
explain select * from employees where age >=1001 and age <=2000;
![](https://upload-images.jianshu.io/upload_images/10170978-aec699e66bb8f452.png&originHeight=60&originWidth=1124&size=31219&status=done&style=stroke&width=1124?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
还原最初索引状态:
ALTER TABLE `employees`
DROP INDEX `idx_age`;
索引使用总结
假设 index(a,b,c)
![](https://upload-images.jianshu.io/upload_images/10170978-f53ddddb5a793e07.png&originHeight=286&originWidth=794&size=184779&status=done&style=stroke&width=794?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
like KK% 相当于=常量,%KK 和 %KK% 相当于范围
部分图片来源于网络,版权归原作者,侵删。