• 当使用索引列进行查询的时候尽量不要使用表达式,把计算放到业务层而不是数据库层

      1. select actor_id from actor where actor_id=4;
      2. select actor_id from actor where actor_id+1=5;
    • 尽量使用主键查询,而不是其他索引,因为主键查询不会触发回表查询

    • 使用前缀索引

    • 使用索引扫描来排序

    • union all,in,or都能够使用索引,但是推荐使用in

      explain select  from actor where actor_id = 1 union all select  from actor where actor_id = 2;
      explain select * from actor where actor_id in (1,2);
      explain select * from actor where actor_id = 1 or actor_id =2;
      
    • 范围列可以用到索引

      • 范围条件是:<、>
      • 范围列可以用到索引,但是范围列后面的列无法用到索引,索引最多用于一个范围列
    • 强制类型转换会全表扫描

      explain select * from user where phone=13800001234;
      --不会触发索引
      
      explain select * from user where phone='13800001234';
      --触发索引
      
    • 更新十分频繁,数据区分度不高的字段上不宜建立索引

      • 更新会变更B+树,更新频繁的字段建议索引会大大降低数据库性能
      • 类似于性别这类区分不大的属性,建立索引是没有意义的,不能有效的过滤数据
      • 一般区分度在80%以上的时候就可以建立索引,区分度可以使用 count(distinct(列名))/count(*) 来计算
    • 创建索引的列,不允许为null,可能会得到不符合预期的结果

    • 当需要进行表连接的时候,最好不要超过三张表,因为需要join的字段,数据类型必须一致

    • 能使用limit的时候尽量使用limit

    • 单表索引建议控制在5个以内

    • 单索引字段数不允许超过5个(组合索引)

    • 创建索引的时候应该避免以下错误概念

      1. 索引越多越好
      2. 过早优化,在不了解系统的情况下进行优化