SQL语句里会导致性能问题的3个场景

发布时间:2020-07-17 13:26:20 作者:nineteens
来源:网络 阅读:363

  条件字段做函数操作:

  破坏了索引值的有序性,所以优化器决定放弃走树搜索功能,但不是放弃走索引,只是不能使用索引的快速定位功能,可以使用使用全索引扫描,当然也可能会直接遍历主键索引。

  mysql> desc select * from t where substr(age,1,1)='1';

  | id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |

  | 1 | SIMPLE | t | NULL | ALL | NULL | NULL | NULL | NULL | 10 | 100.00 | Using where |

  1 row in set, 1 warning (0.00 sec)

  mysql> desc select * from t where age like '1%';

  | id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |

  | 1 | SIMPLE | t | NULL | range | idx_age | idx_age | 15 | NULL | 1 | 100.00 | Using index condition |

  1 row in set, 1 warning (0.00 sec)

  上面例子中,age字段是varchar(4)类型且列上有idx_age索引,从两种查询方式和执行计划可以明显看出对条件字段做函数操作和对传参做操作的区别。

  隐式类型转换:

  mysql> desc select * from t where age=20;

  | id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |

  | 1 | SIMPLE | t | NULL | ALL | idx_age | NULL | NULL | NULL | 10 | 10.00 | Using where |

  1 row in set, 3 warnings (0.00 sec)

  mysql> show warnings;

  | Level | Code | Message |

  | Warning | 1739 | Cannot use ref access on index 'idx_age' due to type or collation conversion on field 'age' |

  | Warning | 1739 | Cannot use range access on index 'idx_age' due to type or collation conversion on field 'age' |

  | Note | 1003 | /* select#1 */ select `test`.`t`.`id` AS `id`,`test`.`t`.`city` AS `city`,`test`.`t`.`name` AS `name`,`test`.`t`.`age` AS `age` from `test`.`t` where (`test`.`t`.`age` = 20) |

  3 rows in set (0.00 sec)

  mysql> desc select * from t where age='20';

  | id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |

  | 1 | SIMPLE | t | NULL | ref | idx_age | idx_age | 15 | const | 5 | 100.00 | NULL |

  1 row in set, 1 warning (0.00 sec)

  mysql> show warnings;

  | Level | Code | Message |

  | Note | 1003 | /* select#1 */ select `test`.`t`.`id` AS `id`,`test`.`t`.`city` AS `city`,`test`.`t`.`name` AS `name`,`test`.`t`.`age` AS `age` from `test`.`t` where (`test`.`t`.`age` = '20') |

  1 row in set (0.00 sec)无锡好的×××医院 http://www.zzchnk.com/

  上面例子中,age字段是varchar(4)类型且列上有idx_age索引,从两种查询方式和执行计划,以及执行完Mysql的warning中我们都能看出,在 MySQL 中,字符串和数字做比较的话,是将字符串转换成数字。所以select * from t where age=20时,数据库相当于是先对age字段做了运算(隐式转换),然后再和20相比,这也和上面条件字段做函数操作不走索引的快速定位功能相呼应。

  隐式字符编码转换:

  字符集utf8mb4是utf8的超集,在程序设计语言里面,做自动类型转换的时候,为了避免数据在转换的过程中由于截断导致数据错误,也都是"按数据长度增长的方向"进行转换的。

  所以说当这两个字段比较时,会先把utf8字符串转换成uft8mb4字符集,再做比较,就有相当于在uft8的列上做了函数操作(隐式转换)

  3种情况其实本质是一样的,就是在原本计划走索引快速扫描的列上进行了函数操作(显式or隐式),导致其不能“按计划行事”


推荐阅读:
  1. 导致Hbase挂掉的场景
  2. 导致Oracle性能抖动的参数提醒

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

mysql 致性

上一篇:centos7安装php7

下一篇:Android切近实战(七)

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》