mysql 12 SQL优化策略

SQL优化的几大策略

1  尽量全值匹配

   即条件里全用索引字段

2 最近左前缀原则

   让索引不失效的一种原则,简单来说比如建立了一个复合索引index(name,age, sex)  根据最左前缀原则,相当于建立了

index(name)  index(name,age)  index(name,age,sex)   同时用了这3个当中的一个就会使用到索引

也可以理解为火车头(name) 火车车身(age) 火车尾巴(sex)

3  不在索引列上做任何操作(计算,函数,类型转换等),会导致索引失效

4  范围查询放最后

        如果使用了范围查询,会导致范围查询以后的索引失效,而它本身继续生效

有复合索引index(name,age, sex)

 如  select * from table1 where  name = '赵刚'  and  age > 35 and sex = '男'    会导致最后面一个索引sex失效,但name和age依然生效

5  覆盖索引尽量用

    查询列只用索引字段,因为索引生效,肯定好过全表扫描

6 不等于要慎用

     因为无法使用索引,只能全表扫描

7  null/ not null 对索引的影响?

index(name,age,sex)

列是否允许为null where 条件 是否使用索引 原因
is not null * from where name is null 推测优化器做了优化,肯定不满足,所以连表都不会扫
is not null * from where name is not null 推测优化器做了优化,where总是满足 类似1=1 
null * from where name is null  
null * from where name is not null  

8  like查询要当心

     通配符不能放到前面 要放后面

     name like  '%july'  索引失效       name like   'july%' 索引生效

9  字符串要加引号

    否则可能引起类型转换,导致索引失效

name = 917 (索引失效)       name = '917'  

10  or 改union 效率高

      如 select * from  table1 where name = 'july'  or  name = '赵刚'    索引失效

     改为  

     select * from  table1 where name = 'july'

     union

     select * from  table1 where name = '赵刚'   索引生效

      

口诀

全值匹配我最爱 , 最左前缀要遵守

带头大哥不能死 ,中间兄弟不能断

索引列上少计算 ,范围之后全失效

LIKE百分写最右 ,覆盖索引不写*

不等空值还有or  ,索引影响要注意

varchar引号不可丢 ,SQL优化有诀窍

insert 语句优化

1 提交前关闭自动递交

2 尽量批量insert语句

3 推荐使用myIsam存储引擎(生产环境别用)

如果手头的数据,不是insert语句,而是从数据库导出的数据

那么直接   load  data INFILE  '文件路径'  into table  tableName1 

即可把数据写入表,比一般insert快几十倍

原文地址:https://www.cnblogs.com/hup666/p/13407349.html