Home > Database > Mysql Tutorial > Practice (1)--MySQL performance optimization

Practice (1)--MySQL performance optimization

coldplay.xixi
Release: 2020-09-18 18:00:23
forward
2921 people have browsed it

Practice (1)--MySQL performance optimization

Related learning recommendations: mysql tutorial

##Preface

    MySQL index underlying data structure and algorithm
  • MySQL performance optimization principle - Part 1
The first two articles have finished the index underlying data structure and performance optimization principle basic concepts. This article will talk about specific practices. Divided into two parts, this is the first part of practice. For a data-centric application, the quality of the database directly affects the performance of the program, so database performance is crucial. Generally speaking, to ensure the efficiency of the database, the following four aspects must be done:

    Database table design
  1. SQL statement optimization
  2. Database parameter configuration
  3. Appropriate hardware resources and operating system
In addition, using appropriate stored procedures can also improve performance. This order also shows the impact of the four aspects on performance.

Database table design

A common understanding of the three paradigms is of great benefit to database design. In database design, in order to better apply the three paradigms, it is necessary to understand the three paradigms popularly.

First normal form: 1NF - ensuring atomicity

is the atomicity constraint

on the attribute, which requires the attribute (column) to be atomic and cannot be decomposed; (as long as All relational databases satisfy 1NF)

Second normal form: 2NF - ensure that each column in the table is related to the primary key

is the unique constraint on

records , requirements The record has a unique identifier, that is, the uniqueness of the entity;

First satisfy 1NF, and then each table must have a primary key, and ensure that each column is related to the primary key, not part of the primary key (mainly for joint primary keys). In other words, only one type of data is stored in a table instead of multiple types of data.

Error Demonstration: Wrong design of product order information

Practice (1)--MySQL performance optimization

Correct Demonstration: Correct design of product order information

Practice (1)--MySQL performance optimization
Third Normal Form: 3NF - Ensure that each column is directly related to the primary key, not indirectly related

3NF is a constraint on

field redundancy, which requires that fields are not redundant.

The third normal form needs to ensure that each column of data in the data table is directly related to the primary key and cannot be indirectly related. Transitive dependencies are not allowed, for example, non-primary key column A depends on non-primary key column B, and non-primary key column B depends on the primary key.

关键字段 -> 非关键字段x -> 非关键字段y复制代码
Copy after login

Case 1:

For example, when designing an order data table, you can use the customer number as a foreign key to establish a corresponding relationship with the order table. You cannot add other information about the customer (such as name, company, etc.) fields to the order form. The design shown in the following two tables is a database table that satisfies the third normal form.

Practice (1)--MySQL performance optimization
##Case 2:

Assume that the student relationship table is

Student

(Student number, name, age, college, college location, college phone number), the key word is the single keyword "student number", because there is the following determination relationship: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false;">(学号)-&gt; (姓名、年龄、所在学院、学院地点、学院电话)复制代码</pre><div class="contentsignin">Copy after login</div></div> That is, there is a non-key field "college location" , the transfer function dependence of "college phone number" on the key field "student number". It will also have data redundancy, update anomalies, insertion anomalies and deletion anomalies. Correctly, the student relationship table should be divided into the following two tables:

Student: (student number, name, age, college)
  • College: (college, location, phone number)
  • Advantages and disadvantages of normalization

Advantages of normalization:

##Less duplicate data and no redundancy;

    Fast maintenance and updates;
  1. Normalized tables are smaller and can be run in memory.
  2. Disadvantages of normalization:

Querying often requires many associations, which increases the cost of querying. It may also invalidate some indexing strategies because normalization places columns in different tables that would otherwise belong to the same index in one table.

Advantages and disadvantages of denormalization

Advantages of denormalization:

Avoid correlation, almost all data can be displayed in one table .

    Can design effective indexes.
  1. Disadvantages of denormalization:

There is a lot of redundant data, which is less troublesome to maintain. It is also easy to lose important information when deleting data.

数据表设计的建议

没有冗余的数据库设计可以做到,但是,没有冗余的数据库未必是最好的数据库,有时为列提高运行效率,就必须降低范式标准,适当保留冗余数据。具体做法:在概念数据模型设计时遵守第三范式,降低范式标准的工作放到物理数据模型设计时考虑。降低范式就是增加字段,允许冗余。

另外,《阿里巴巴Java开发手册》,数据库的表设计允许适当冗余,以提升SQL查询的性能,避免表的关联查询。

适度冗余,减少join的关联

冗余更新频率不高,但是查询频率极高的字段。如订单中的商品名称、微博发帖中的用户昵称。

Practice (1)--MySQL performance optimization

大字段垂直拆分

Practice (1)--MySQL performance optimization

如把博客列表中的内容拆分出去,访问列表的时候不读取博客内容,为纵深的逻辑关系。

大表水平拆分

举例说明:在一个论坛系统里,管理员经常会发一些帖子,这些帖子要求在每个分类列表里都要置顶。

  • 设计方案一:在发帖表里增加一列用来标示是否是管理员发帖,这样在每个分类列表展示时就需要对发帖表查询两次,一次是置顶帖,一次是普通帖,然后将两次结果合并。如果发帖表内容较大时,查询置顶帖的性能开销会比较大。
  • 设计方案二:将置顶帖存放在一个单独的置顶表里。因为置顶帖数量相比会很少,但访问频率很高,这样从发帖表里分拆开来,访问的性能开销会少很多。

合适的数据类型

如果数据量一样,但数据类型更小的话,数据存放同样的数据就会占用更少的空间,这样检索同样的数据所带来的IO 消耗自然会降低,性能也就很自然的得到提升。此外,MySQL 对不同类型的数据,处理方式也不一样,比如在运算或者排序操作中,越简单的数据类型操作性能越高,所以对于要频繁进行运算或者排序的字段尽量选择简单的数据类型。

Practice (1)--MySQL performance optimization

SQL语句优化

SQL优化的一般步骤

  1. 通过show status命令了解各种SQL的执行频率;
  2. 定位执行效率较低的SQL语句-(重点select);
  3. 通过explain分析低效率的SQL;
  4. 确定问题并采取相应的优化措施。
-- select语句分类SelectDml数据操作语言(insert update delete)
dtl 数据事物语言(commit rollback savepoint)Ddl数据定义语言(create alter drop..)
Dcl(数据控制语言) grant revoke-- Show status 常用命令--查询本次会话Show session status like &#39;com_%&#39;;     //show session status like &#39;Com_select&#39;--查询全局Show global status like &#39;com_%&#39;;-- 给某个用户授权grant all privileges on *.* to &#39;abc&#39;@&#39;%&#39;;--为什么这样授权 &#39;abc&#39; 表示用户名  &#39;@&#39; 表示host, 查看一下mysql->user表就知道了--回收权限revoke all on *.* from &#39;abc&#39;@&#39;%&#39;;--刷新权限[也可以不写]flush privileges;复制代码
Copy after login

SQL语句优化-show参数

MySQL客户端连接成功后,通过使用 show [session|global] status 命令可以提供服务器状态信息。其中的session来表示当前的连接的统计结果,global来表示自数据库上次启动至今的统计结果。默认是session级别的。

show status like &#39;Com_%&#39;;复制代码
Copy after login

其中, Com_XXX 表示 XXX 语句所执行的次数。 重点注意:Com_select,Com_insert,Com_update,Com_delete 通过这几个参数,可以了解到当前数据库的应用是以插入更新为主还是以查询操作为主,以及各类的SQL大致的执行比例是多少。

还有几个常用的参数便于用户了解数据库的基本情况。Connections:试图连接MySQL服务器的次数Uptime:服务器工作的时间(单位秒)Slow_queries:慢查询的次数 (默认是慢查询时间10s)

show status like &#39;Connections&#39;;show status like &#39;Uptime&#39;;show status like &#39;Slow_queries&#39;;复制代码
Copy after login

查询MySQL的慢查询时间

show variables like &#39;long_query_time&#39;;复制代码
Copy after login

修改MySQL慢查询时间

set long_query_time=2;复制代码
Copy after login

SQL语句优化-定位慢查询

上面我们介绍了获取MySQL数据库的一些运行状态是如何查询

  • 比如当前MySQL运行的时间: show status like &#39;Uptime&#39;;
  • 一共执行了多少次select/update/delete.. /show status like &#39;Com_%&#39;;
  • 当前连接数

定位慢查询

如何从一个项目中快速定位执行速度慢的语句(定位慢查询)

show variables like &#39;%query%&#39;;复制代码
Copy after login
Practice (1)--MySQL performance optimization
  • slow_query_log 默认是off关闭的,使用时,需要改为on 打开      
  • slow_query_log_file 记录的是慢日志的记录文件
  • long_query_time 默认是10S,每次执行的sql达到这个时长,就会被记录

查看慢查询状态

Slow_queries 记录的是慢查询数量 当有一条sql执行一次比较慢时,这个vlue就是1 (记录的是本次会话的慢sql条数)

show status like &#39;%slow_queries%&#39;;复制代码
Copy after login
Practice (1)--MySQL performance optimization

注意:

  1. 如何打开慢查询 : SET GLOBAL slow_query_log = ON;
  2. 将默认时间改为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,&#39;a&#39;,&#39;2020-09-16 14:26:11&#39;), (2,&#39;b&#39;,&#39;2020-09-16 14:26:11&#39;), (3,&#39;c&#39;,&#39;2020-09-16 14:26:11&#39;);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,&#39;film0&#39;),(1,&#39;film1&#39;),(2,&#39;film2&#39;);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);复制代码
Copy after login
explain select * from actor;复制代码
Copy after login
Practice (1)--MySQL performance optimization

查询中的每个表会输出一行,如果有两个表通过join连接查询,那么会输出两行。每一列具体的说明在后面进行说明。

Explain 两个变种

  1. explain extended

会在 explain 的基础上额外提供一些查询优化的信息。紧随其后通过 show warnings 命令可以得到优化后的查询语句,从而看出优化器优化了什么。额外还有 filtered 列,是一个半分比的值,rows * filtered/100 可以估算出将要和 explain 中前一个表进行连接的行数(前一个表指 explain 中的id值比当前表id值小的表)。

explain extended select * from film where id = 1;复制代码
Copy after login
Practice (1)--MySQL performance optimization
show warnings;复制代码
Copy after login
Copy after login
Practice (1)--MySQL performance optimization
  1. 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;复制代码
Copy after login
Practice (1)--MySQL performance optimization
  • 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;复制代码
Copy after login

未关闭MySQL5.7新特性对衍生表的合并优化,如下:

Practice (1)--MySQL performance optimization
#关闭mysql5.7新特性对衍 生表的合并优化set session optimizer_switch=&#39;derived_merge=off&#39;; 
复制代码
Copy after login
Practice (1)--MySQL performance optimization
#还原默认配置set session optimizer_switch=&#39;derived_merge=on&#39;; 
复制代码
Copy after login
  • union :在 union 中的第二个和随后的 select
explain select 1 union all select 1;复制代码
Copy after login
Practice (1)--MySQL performance optimization

table 列

这一列表示 explain 的一行正在访问哪个表。 当 from 子句中有子查询时,table列是 格式,表示当前查询依赖 id=N 的查 询,于是先执行 id=N 的查询。 当有 union 时,UNION RESULT 的 table 列的值为,1和2表示参与 union 的 select 行id。

type 列

这一列表示关联类型或访问类型,即MySQL决定如何查找表中的行,查找数据行记录的大概范围。

依次从最优到最差分别为:

system > const > eq_ref > ref > range > index > ALL复制代码
Copy after login

一般来说,得保证查询达到 range 级别,最好达到 ref

NULL:MySQL 能够在优化阶段分解查询语句,在执行阶段用不着再访问表或索引。例如:在索引列中选取最小值,可以单独查找索引来完成,不需要在执行时访问表。

explain select min(id) from film;复制代码
Copy after login
Copy after login
Practice (1)--MySQL performance optimization

systemconst :MySQL 能对查询的某部分进行优化并将其转化成一个常量(可以看 show warnings 的)。用于 primary keyunique key 的所有列与常数比较时,所以表最多有一个匹配行,读取1次,速度比较快。system 是 const 的特例,表里只有一条元组匹配时为 system。

explain extended select * from (select * from film where id = 1) tmp;复制代码
Copy after login
Practice (1)--MySQL performance optimization
show warnings;复制代码
Copy after login
Copy after login
Practice (1)--MySQL performance optimization

eq_ref :primary key 或 unique key 索引的所有部分被连接使用,最多只会返回一条符合条件的记录。这可能实在 const 之外最好的连接类型了,简单的 select 查询不会出现这种 type。

explain select * from film_actor left join film on film_actor.film_id = film.id;复制代码
Copy after login
Practice (1)--MySQL performance optimization

ref :相比 eq_ref ,不使用唯一索引,而是使用普通索引或者唯一性索引的部分前缀,索引要和某个值相比较,可能会找到多个符合条件的行。

(1)简单 select 查询,name 是普通索引(非唯一索引)

explain select * from film where name = &#39;film1&#39;;复制代码
Copy after login
Practice (1)--MySQL performance optimization

(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;复制代码
Copy after login
Practice (1)--MySQL performance optimization

range : 范围扫描通常出现在 in()、betwwen、>、<、>= 等操作中。使用一个索引来检索给定范围的行。

explain select * from actor where id > 1;复制代码
Copy after login
Practice (1)--MySQL performance optimization

index :扫描全表索引,通过比 ALL 快一些。

explain select * from film;复制代码
Copy after login
Practice (1)--MySQL performance optimization

ALL :即全表扫描,意味着MySQL需要从头到尾去查找所需要的行。通常情况下这需要增加索引来进行优化了。

explain select * from actor复制代码
Copy after login
Practice (1)--MySQL performance optimization

possible_keys 列

这一列显示查询可能使用哪些索引来查找。 explain 时可能出现 possible_keys 有列,而 key 显示 NULL 的情况,这种情况是因为表中数据不多,mysql认为索引对此查询帮助不大,选择了全表查询。 如果该列是NULL,则没有相关的索引。在这种情况下,可以通过检查 where 子句看是否可以创造一个适当的索引来提高查询性能,然后用 explain 查看效果。

key 列

这一列显示mysql实际采用哪个索引来优化对该表的访问。 如果没有使用索引,则该列是 NULL。如果想强制mysql使用或忽视possible_keys列中的索 引,在查询中使用 force indexignore 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;复制代码
Copy after login
Practice (1)--MySQL performance optimization

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;复制代码
Copy after login
Practice (1)--MySQL performance optimization

(2)Using where :使用 where 语句来处理结果,查询的列未被索引覆盖

explain select * from actor where name = &#39;a&#39;;复制代码
Copy after login
Practice (1)--MySQL performance optimization

(3)Using index condition :查询的列不完全被索引覆盖,where 条件中是一个前导列的范围

explain select * from film_actor where film_id > 1;复制代码
Copy after login
Practice (1)--MySQL performance optimization

(4)Using temporary :MySQL 需要创建一张临时表来处理查询。出现这种情况一般是要进行优化的,首先是想到用索引来优化。

  • actor.name没有索引,此时创建了张临时表来distinct
explain select distinct name from actor;复制代码
Copy after login
Practice (1)--MySQL performance optimization
  • film.name建立了idx_name索引,此时查询时extra是using index,没有用临时表
explain select distinct name from film;复制代码
Copy after login
Practice (1)--MySQL performance optimization

(5)Using filesort : 将用外部排序而不是索引排序,数据较小时从内存排序,否则需要在磁盘 完成排序。这种情况下一般也是要考虑使用索引来优化的。

  • actor.name没有索引,会浏览 actor 整个表,保存排序关键字 name 和对应的 id,然后排序 name 并检索行记录。
explain select * from actor order by name;复制代码
Copy after login
Practice (1)--MySQL performance optimization
  • film.name建立了idx_name索引,此时查询时extra是using index
explain select * from film order by name;复制代码
Copy after login
Practice (1)--MySQL performance optimization

(6)Select tables optimized away :使用某些聚合函数(比如 max、min)来访问存在索引 的某个字段是

explain select min(id) from film;复制代码
Copy after login
Copy after login
Practice (1)--MySQL performance optimization

SQL语句优化-索引最佳实践

# 示例表CREATE TABLE`employees`(`id` int(11) NOT NULL AUTO_INCREMENT,`name` varchar(24) NOT NULL DEFAULT &#39;&#39; COMMENT &#39;姓名&#39;,`age` int(11) NOT NULL DEFAULT &#39;0&#39; COMMENT &#39;年龄&#39;,`position` varchar(20) NOT NULL DEFAULT &#39;&#39; COMMENT &#39;职位&#39;,`hire_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT &#39;入职时间&#39;,
PRIMARY KEY (`id`), KEY `idx_name_age_position` (`name`,`age`,`position`) USING BTREE
 )ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COMMENT=&#39;员工记录表&#39;; 
INSERT INTO employees(name,age,position,hire_time)VALUES(&#39;ZhangSan&#39;,23,&#39;Manager&#39;,NOW());INSERT INTO employees(name,age,position,hire_time)VALUES(&#39;HanMeimei&#39;, 23,&#39;dev&#39;,NOW());INSERT INTO employees(name,age,position,hire_time) VALUES(&#39;Lucy&#39;,23,&#39;dev&#39;,NOW());复制代码
Copy after login

全值匹配

EXPLAIN SELECT * FROM employees WHERE name= &#39;ZhangSan&#39;;复制代码
Copy after login
Practice (1)--MySQL performance optimization
EXPLAIN SELECT * FROM employees WHERE name= &#39;ZhangSan&#39; AND age = 22;复制代码
Copy after login
Practice (1)--MySQL performance optimization
EXPLAIN SELECT * FROM employees WHERE name= &#39;ZhangSan&#39; AND age = 22 AND position =&#39;manager&#39;;复制代码
Copy after login
Practice (1)--MySQL performance optimization

最左前缀法则

如果索引了多列,要遵守最左前缀法则。指的是查询从索引的最左前列开始并且不跳过索引中的列。

EXPLAIN SELECT * FROM employees WHERE age = 22 AND position =&#39;manager&#39;;复制代码
Copy after login
Practice (1)--MySQL performance optimization
EXPLAIN SELECT * FROM employees WHERE position = &#39;manager&#39;;复制代码
Copy after login
Practice (1)--MySQL performance optimization
EXPLAIN SELECT * FROM employees WHERE name = &#39;ZhangSan&#39;;复制代码
Copy after login
Practice (1)--MySQL performance optimization

不在索引列上做任何操作

不在索引列上做任何操作(计算、函数、(自动or手动)类型转换),会导致索引失效而转向全表扫描。

EXPLAIN SELECT * FROM employees WHERE name = &#39;ZhangSan&#39;;EXPLAIN SELECT * FROM employees WHERE left(name,3) = &#39;ZhangSan&#39;;复制代码
Copy after login
Practice (1)--MySQL performance optimization

给hire_time增加一个普通索引:

ALTER TABLE `employees`ADD INDEX `idx_hire_time` (`hire_time`) USING BTREE;复制代码
Copy after login
EXPLAIN select * from employees where date(hire_time) =&#39;2020-09-30&#39;;复制代码
Copy after login
Practice (1)--MySQL performance optimization

转化为日期范围查询,会走索引:

EXPLAIN select * from employees where hire_time >=&#39;2020-09-30 00:00:00&#39; and hire_time <=&#39;2020-09-30 23:59:59&#39;;复制代码
Copy after login
Practice (1)--MySQL performance optimization

还原最初索引状态

ALTER TABLE `employees`DROP INDEX `idx_hire_time`;复制代码
Copy after login

存储引擎不能使用索引中范围条件右边的列

EXPLAIN SELECT * FROM employees WHERE name= &#39;ZhangSan&#39; AND age = 22 AND position =&#39;manager&#39;;EXPLAIN SELECT * FROM employees WHERE name= &#39;ZhangSan&#39; AND age > 22 AND position =&#39;manager&#39;;复制代码
Copy after login
Practice (1)--MySQL performance optimization

尽量使用覆盖索引

尽量使用覆盖索引(只访问索引的查询(索引列包含查询列)),减少select *语句。

EXPLAIN SELECT name,age FROM employees WHERE name= &#39;ZhangSan&#39; AND age = 23 AND position =&#39;manager&#39;;复制代码
Copy after login
Practice (1)--MySQL performance optimization
EXPLAIN SELECT * FROM employees WHERE name= &#39;ZhangSan&#39; AND age = 23 AND position =&#39;manager&#39;;复制代码
Copy after login
Practice (1)--MySQL performance optimization

mysql在使用不等于(!=或者<>)的时候无法使用索引会导致全表扫描

EXPLAIN SELECT * FROM employees WHERE name != &#39;ZhangSan&#39;;复制代码
Copy after login
Practice (1)--MySQL performance optimization

is null、is not null 也无法使用索引

EXPLAIN SELECT * FROM employees WHERE name is null复制代码
Copy after login
Practice (1)--MySQL performance optimization

like以通配符开头('%abc...')mysql索引失效会变成全表扫描操作

EXPLAIN SELECT * FROM employees WHERE name like &#39;%Zhang&#39;复制代码
Copy after login
Practice (1)--MySQL performance optimization
EXPLAIN SELECT * FROM employees WHERE name like &#39;Zhang%&#39;复制代码
Copy after login
Practice (1)--MySQL performance optimization

问题:解决like'%字符串%'索引不被使用的方法?

  • 使用覆盖索引,查询字段必须是建立覆盖索引字段
EXPLAIN SELECT name,age,position FROM employees WHERE name like &#39;%Zhang%&#39;;复制代码
Copy after login
Practice (1)--MySQL performance optimization
  • 如果不能使用覆盖索引则可能需要借助搜索引擎

字符串不加单引号索引失效

EXPLAIN SELECT * FROM employees WHERE name = &#39;1000&#39;; 
EXPLAIN SELECT * FROM employees WHERE name = 1000;复制代码
Copy after login
Practice (1)--MySQL performance optimization

少用or或in

少用or或in,用它查询时,mysql不一定使用索引,mysql内部优化器会根据检索比例、 表大小等多个因素整体评估是否使用索引,详见范围查询优化。

EXPLAIN SELECT * FROM employees WHERE name = &#39;ZhangSan&#39; or name = &#39;HanMeimei&#39;;复制代码
Copy after login
Practice (1)--MySQL performance optimization

范围查询优化

给年龄添加单值索引

ALTER TABLE`employees`ADD INDEX `idx_age` (`age`)USING BTREE;复制代码
Copy after login
explain select * from employees where age >=1 and age <=2000;复制代码
Copy after login
Practice (1)--MySQL performance optimization

没走索引原因:mysql内部优化器会根据检索比例、表大小等多个因素整体评估是否使用索引。比如这个例子,可能是由于单次数据量查询过大导致优化器最终选择不走索引 优化方法:可以讲大的范围拆分成多个小范围。

explain select * from employees where age >=1 and age <=1000;explain select * from employees where age >=1001 and age <=2000;复制代码
Copy after login
Practice (1)--MySQL performance optimization

还原最初索引状态:

ALTER TABLE `employees`DROP INDEX `idx_age`;复制代码
Copy after login

索引使用总结

假设 index(a,b,c)

Practice (1)--MySQL performance optimization

like KK% 相当于=常量,%KK 和 %KK% 相当于范围

想了解更多编程学习,敬请关注php培训栏目!

The above is the detailed content of Practice (1)--MySQL performance optimization. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:juejin.im
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template