SQL语句及索引的优化

  • 尽量避免使用子查询
    列:select * from table1 id(select id from table2 where name=’jiushi’);
    子查询在Mysql5.5版本中先查外表再匹配内表,而不是先查询table2,当外表数据很大时,查询速度会非常慢;
    在Mysql5.6版本中采用join关联方式对其进行了优化,这条SQL会自动转为select table1.* from table1 join table2 on table1.id=table2.id
    Ps:优化只针对select有效,对Update/Delete子查询无效,生产环境应避免使用子查询;

  • 避免使用函数索引
    列:select * from table where year(StartTime) >= 2016;
    因为Mysql不像Oracle一样支持函数索引,即使StratTime字段有索引,也会全表扫描;
    解决方案:select * from table where StartTime>=’2020-12-14’

  • 用IN来替换OR
    select * from table where id=10 or id=11 or id=12;
    select * from table where id in(10,11,12);
    Mysql对于In做了相应的优化,即使IN中的常量全部存储在一个数组里面,而且这个数组是排好序的。但是如果数值较多,产生的消耗也很大。如果查询的数值较少且连续的数值,能用between就不要用IN了;

  • like模糊查询前缀%号、%%双百分号、_下划线查询查询非索引列或✳无法使用到索引,如果查询的是索引列则可以;
    select * from table where name like ‘%jiu%’;

  • —>改进
    select * from table where name like ‘jiushi%’;
    Ps:Mysql5.7支持全文检索且支持中文;

  • 查询适当的记录limit m,n 而不要查询多余的记录

    1
    2
    select id,name from table limit 949494,20

    使用上面这条SQL语句分页查询,当数据量特别大的时候,查询会越来越慢;
    优化:

    1
    select id,name from table where id>949494 limit 20

//TODO