MySQL实战18の索引的函数操作

  1. 条件字段函数操作
    select count(*) from tradelog where month(t_modified)=7;

     修改为:

    select count(*) from tradelog where t_modified>=date_format('2018-7-1''%Y%m%d'and 
    t_modified<date_format('2018-8-1''%Y%m%d');
  2. 隐式类型转换(MySQL中字符串和数字作比较,是把字符串转换成数字)
    select * from tradelog where tradeid=110717;
    tradeid为varchar类型,转换为下面语句再执行
    select * from tradelog where CAST(tradid AS signed int)=110717;

     修改为:

    select * from tradelog where tradeid='110717';
  3. 隐式字符编码转换
    1.修改表的字符集
    alter table trade_detail modify tradeid varchar(32) CHARACTER SET utf8mb4 default null;
    2.修改SQL语句
    select d.* from tradelog l , trade_detail d where d.tradeid=CONVERT(l.tradeid USING utf8) and l.id=2; 

总结

对索引字段做函数操作,可能会破坏索引值的有序性,因此优化器决定放弃执行树搜索功能,导致执行效率低。

在写SQL语句时或者进行SQL优化过程中,使用explain查看和分析执行计划是一个很好的习惯。

原文地址:https://time.geekbang.org/column/article/74059(极客时间付费专栏)

原文地址:https://www.cnblogs.com/yangjiming/p/10169167.html