MySQL实战45讲 18

18 | 为什么这些SQL语句逻辑相同,性能却差异巨大?

在 MySQL 中,有很多看上去逻辑相同,但性能却差异巨大的 SQL 语句。对这些语句使用不当的话,就会不经意间导致整个数据库的压力变大。

三个案例

案例一:条件字段函数操作

假设你现在维护了一个交易系统,其中交易记录表 tradelog 包含交易流水号(tradeid)、交易员 id(operator)、交易时间(t_modified)等字段,先忽略其他字段。这个表的建表语句如下:

CREATE TABLE tradelog (
  id int(11) NOT NULL,
  tradeid varchar(32) DEFAULT NULL,
  operator int(11) DEFAULT NULL,
  t_modified datetime DEFAULT NULL,
  PRIMARY KEY (id),
  KEY tradeid (tradeid),
  KEY t_modified (t_modified)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

现在已经记录了从 2016 年初到 2018 年底的所有数据,有一个需求是要统计发生在所有年份中 7 月份的交易记录总数。SQL 语句可能会这么写:

select count(*) from tradelog where month(t_modified)=7;

结果发现,在返回结果之前,执行了很长时间。

[En]

It was found that it took a long time to execute before the result was returned.

原因:如果对字段做了函数计算,就用不上索引了,这是 MySQL 的规定。

Q:为什么条件是 where t_modified=’2018-7-1’的时候可以用上索引,而改成 where month(t_modified)=7 的时候就不行了?

A:

由于加了 month() 函数操作,MySQL 无法再使用索引快速定位功能,而只能使用全索引扫描

下面是这个 t_modified 索引的示意图。方框上面的数字就是 month() 函数对应的值。

MySQL实战45讲 18

如果你的 SQL 语句条件用的是 where t_modified=’2018-7-1’的话,引擎就会按照上面绿色箭头的路线,快速定位到 t_modified=’2018-7-1’需要的结果。

B+ 树提供的这个 快速定位能力,来源于 同一层兄弟节点的有序性

但是,如果计算 month() 函数的话,传入 7 的时候,在树的第一层就不知道该怎么办了。

也就是说, 对索引字段做函数操作,可能会破坏索引值的有序性,因此优化器就决定放弃走树搜索功能。

需要注意的是, 优化器并不是要放弃使用这个索引

在这个例子里,放弃了 树搜索_功能,优化器可以选择遍历 主键索引,也可以选择遍历 索引 t_modified,优化器对比 索引大小后发现, 索引 t_modified 更小,遍历这个索引比遍历主键索引来得更快(注意是 遍历_)。因此最终还是会选择索引 t_modified。

使用 explain 命令,查看一下这条 SQL 语句的执行结果。

MySQL实战45讲 18

key=”t_modified”表示的是,使用了 t_modified 这个索引;我在测试表数据中插入了 10 万行数据,rows=100335, 说明这条语句扫描了整个索引的所有值;Extra 字段的 Using index,表示的是使用了 覆盖索引

也就是说,由于在 t_modified 字段加了 month() 函数操作,导致了 全索引扫描。为了能够用上 索引的快速定位能力,我们就要把 SQL 语句改成 基于字段本身的范围查询。按照下面这个写法,优化器就能按照我们预期的,用上 t_modified 索引的快速定位能力了。

select count(*) from tradelog where
    -> (t_modified >= '2016-7-1' and t_modified (t_modified >= '2017-7-1' and t_modified (t_modified >= '2018-7-1' and t_modified

即使是对于不改变有序性的函数,也不会考虑使用索引。比如,对于 select * from tradelog where id + 1 = 10000 这个 SQL 语句,这个加 1 操作并不会改变有序性,但是 MySQL 优化器还是不能用 id 索引快速定位到 9999 这一行。所以,需要你在写 SQL 语句的时候,手动改写成 where id = 10000 -1 才可以。

案例二:隐式类型转换

select * from tradelog where tradeid=110717;

交易编号 tradeid 这个字段上,本来就有索引,但是 explain 的结果却显示,这条语句需要走 全表扫描

原因:tradeid 的字段类型是 varchar(32),而输入的参数却是整型,所以需要做类型转换。

Q:数据类型转换的规则是什么?

A:

将字符串与数字进行比较时,需要将字符串转换为数字

[En]

When comparing a string with a number, it is * to convert a string into a number * .

看 select “10” > 9 的结果:

  1. 如果规则是”将字符串转成数字”,那么就是做数字比较,结果应该是 1;
  2. 如果规则是”将数字转成字符串”,那么就是做字符串比较,结果应该是 0。

MySQL实战45讲 18

Q:为什么有数据类型转换,就需要走全索引扫描?

A:

对于优化器来说,上面的SQL语句相当于:

select * from tradelog where  CAST(tradid AS signed int) = 110717;

换句话说,这条语句触发了我们上面提到的规则:对索引字段进行函数操作,优化器将放弃遍历树搜索功能。

[En]

In other words, this statement triggers the rule we mentioned above: do a functional operation on the index field, and the optimizer will abandon the walking tree search function.

案例三:隐式字符编码转换

假设系统里还有另外一个表 trade_detail,用于记录交易的操作细节。往交易日志表 tradelog 和交易详情表 trade_detail 这两个表里插入一些数据。

CREATE TABLE trade_detail (
  id int(11) NOT NULL,
  tradeid varchar(32) DEFAULT NULL,
  trade_step int(11) DEFAULT NULL, /* 操作步骤 */
  step_info varchar(32) DEFAULT NULL, /* 步骤信息 */
  PRIMARY KEY (id),
  KEY tradeid (tradeid)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

insert into tradelog values(1, 'aaaaaaaa', 1000, now());
insert into tradelog values(2, 'aaaaaaab', 1000, now());
insert into tradelog values(3, 'aaaaaaac', 1000, now());

insert into trade_detail values(1, 'aaaaaaaa', 1, 'add');
insert into trade_detail values(2, 'aaaaaaaa', 2, 'update');
insert into trade_detail values(3, 'aaaaaaaa', 3, 'commit');
insert into trade_detail values(4, 'aaaaaaab', 1, 'add');
insert into trade_detail values(5, 'aaaaaaab', 2, 'update');
insert into trade_detail values(6, 'aaaaaaab', 3, 'update again');
insert into trade_detail values(7, 'aaaaaaab', 4, 'commit');
insert into trade_detail values(8, 'aaaaaaac', 1, 'add');
insert into trade_detail values(9, 'aaaaaaac', 2, 'update');
insert into trade_detail values(10, 'aaaaaaac', 3, 'update again');
insert into trade_detail values(11, 'aaaaaaac', 4, 'commit');

这时候,如果要查询 id=2 的交易的所有操作步骤信息,SQL 语句可以这么写:

select d.* from tradelog l, trade_detail d where d.tradeid=l.tradeid and l.id=2; /* 语句 Q1*/

语句 Q1 的 explain 结果如下

MySQL实战45讲 18
  1. 第一行显示优化器会先在交易记录表 tradelog 上查到 id=2 的行,这个步骤用上了主键索引,rows=1 表示只扫描一行;
  2. 第二行 key=NULL,表示没有用上交易详情表 trade_detail 上的 tradeid 索引,进行了全表扫描。

在这个执行计划里, 是从 tradelog 表中取 tradeid 字段,再去 trade_detail 表里查询匹配字段

因此,我们把 tradelog 称为 驱动表,把 trade_detail 称为 被驱动表,把 tradeid 称为 关联字段

语句 Q1 的执行过程如下:

MySQL实战45讲 18
  • 第 1 步,是根据 id 在 tradelog 表里找到 L2 这一行;
  • 第 2 步,是从 L2 中取出 tradeid 字段的值;
  • 第 3 步,是根据 tradeid 值到 trade_detail 表中查找条件匹配的行。explain 的结果里面第二行的 key=NULL 表示的就是,这个过程是通过遍历主键索引的方式,一个一个地判断 tradeid 的值是否匹配。

第 3 步不符合我们的预期。因为表 trade_detail 里 tradeid 字段上是有索引的,我们本来是 希望通过使用 tradeid 索引能够快速定位到等值的行。但,这里并没有。

原因:因为这两个表的字符集不同,一个是 utf8,一个是 utf8mb4,所以做表连接查询的时候用不上关联字段的索引。

Q:为什么字符集不同就用不上索引呢?

A:如果单独把第 3 步改成 SQL 语句的话,那就是:

select * from trade_detail where tradeid=$L2.tradeid.value;

其中,$L2.tradeid.value 的字符集是 utf8mb4。

字符集 utf8mb4 是 utf8 的超集,所以当这两个类型的字符串在做比较的时候,MySQL 内部的操作是, 先把 utf8 字符串转成 utf8mb4 字符集,再做比较。

这个设定很好理解,utf8mb4 是 utf8 的超集。类似地,在程序设计语言里面,做自动类型转换的时候,为了避免数据在转换过程中由于截断导致数据错误,也都是”按数据长度增加的方向”进行转换的。

因此, 在执行上面这个语句的时候,需要将被驱动数据表里的字段一个个地转换成 utf8mb4,再跟 L2 做比较。

事实上,这一说法相当于以下内容:

[En]

In fact, this statement is equivalent to the following:

select * from trade_detail  where CONVERT(traideid USING utf8mb4)=$L2.tradeid.value;

再次触发上述原理:对索引字段进行函数操作,优化器将放弃树搜索功能。

[En]

Once again triggered the above principle: * do functional operations on the index field, the optimizer will give up the tree search function. *

字符集的差异只是其中一个条件。在连接过程中向被驱动表的索引字段添加函数操作是直接导致被驱动表全表扫描的原因

[En]

The difference in character set is only one of the conditions. * adding a function operation to the index field of the driven table during the connection process is * the reason that directly leads to the full table scan of the driven table * .*

作为对比验证,”查找 trade_detail 表里 id=4 的操作,对应的操作者是谁”,再来看下这个语句和它的执行计划。

select l.operator from tradelog l , trade_detail d where d.tradeid=l.tradeid and d.id=4;

MySQL实战45讲 18

这个语句里 trade_detail 表成了驱动表,但是 explain 结果的第二行显示, 这次的查询操作用上了被驱动表 tradelog 里的索引 (tradeid),扫描行数是 1。

Q:为什么这次能用上被驱动表的 tradeid 索引呢?

A:

假设驱动表 trade_detail 里 id=4 的行记为 R4,那么在连接的时候,被驱动表 tradelog 上执行的就是类似这样的 SQL 语句:

select operator from tradelog  where traideid =$R4.tradeid.value;

这时候 $R4.tradeid.value 的字符集是 utf8, 按照字符集转换规则,要转成 utf8mb4,所以这个过程就被改写成:

select operator from tradelog  where traideid =CONVERT($R4.tradeid.value USING utf8mb4);

这里的 CONVERT 函数是加在输入参数上的这样就可以用上被驱动表的 traideid 索引

如果要优化语句

select d.* from tradelog l, trade_detail d where d.tradeid=l.tradeid and l.id=2;

有两种做法:

  • 比较常见的优化方法是,把 trade_detail 表上的 tradeid 字段的字符集也改成 utf8mb4,这样就没有字符集转换的问题了。
alter table trade_detail modify tradeid varchar(32) CHARACTER SET utf8mb4 default null;
  • 但如果数据量比较大, 或者业务上暂时不能做这个 DDL 的话,那就只能采用修改 SQL 语句的方法了。
mysql> select d.* from tradelog l , trade_detail d where d.tradeid=CONVERT(l.tradeid USING utf8) and l.id=2;

主动把 l.tradeid 转成 utf8,就避免了被驱动表上的字符编码转换

MySQL实战45讲 18

小结

索引字段不能进行函数操作,但是索引字段的参数(=后面的值)可以用函数

补充:字符截断

表结构如下:

CREATE TABLE table_a (
  id int(11) NOT NULL,
  b varchar(10) DEFAULT NULL,
  PRIMARY KEY (id),
  KEY b (b)
) ENGINE=InnoDB;

假设现在表里面,有 100 万行数据,其中有 10 万行数据的 b 的值是’1234567890’, 假设现在执行语句是这么写的:

select * from table_a where b='1234567890abcd';

Q: 这时候,MySQL 会怎么执行呢?

A: 最理想的情况是,MySQL 看到字段 b 定义的是 varchar(10),直接返回空呀。可惜,MySQL 并没有这么做。

那要不,就是把’1234567890abcd’拿到索引里面去做匹配,肯定也没能够快速判断出索引树 b 上并没有这个值,也很快就能返回空结果。但实际上,MySQL 也不是这么做的。

这条 SQL 语句的执行很慢,流程是这样的:

  1. 在传给引擎执行的时候,做了字符截断。因为引擎里面这个行只定义了长度是 10,所以只截了前 10 个字节,就是’1234567890’进去做匹配;
  2. 这样满足条件的数据有 10 万行;
  3. 因为是 select *, 所以要做 10 万次回表;
  4. 但是每次回表以后查出整行,到 server 层一判断,b 的值都不是’1234567890abcd’;
  5. 返回结果是空。

虽然执行过程中可能经过函数操作, 但是最终在拿到结果后,server 层还是要做一轮判断的

Original: https://www.cnblogs.com/ydssx7/p/16528953.html
Author: ydssx
Title: MySQL实战45讲 18

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/505134/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球