SQL优化常用的几种方法

Mysql的SQL优化关键字

Explain

常见SQL优化规则

  1. 查询优化,尽量避免全表扫描.考虑wheregroup by建议索引
  2. 避免在where的语句中使用!=<>操作符,否则引擎将放弃索引进行全表扫描
  3. 避免在where的语句中进行null值判断,否则引擎将放弃索引进行全表扫描
    #例如:
    select id from t where num is null
  4. 避免在where的语句中使用or来连接条件,否则引擎将放弃索引进行全表扫描
#例如: 
select id from t where num=10 or num=20
#优化:
select id from t where num=10 union all select id from t where num=20
  1. 避免在where的语句中使用like关键字, 否则引擎将放弃索引进行全表扫描
    #例如:
    select id from t where name like '%abc%'
    ```
    6. 避免在`where`的语句中使用`in`或者`not in`关键字,否则引擎将放弃索引进行全表扫描

#例如:
select id from t where num in(1,2,3)

#优化:
#查询的数值为连续值,可以使用between进行优化
select id from t where num between 1 and 3


7. 避免在`where`的语句中进行表达式操作,否则引擎将放弃索引进行全表扫描

#例如:
select id from t where num/2=100
#优化:
select id from t where num=100*2

   
8. 避免在`where`的语句中对字段进行函数操作,否则引擎将放弃索引进行全表扫描

#例如:
select id from t where substring(name,1,3)=’abc’
#优化:
select id from t where name like ‘abc%’

#例如:
select id from t where datediff(day,createdate,’2005-11-30’)=0
#优化:
select id from t where createdate>=’2005-11-30’ and createdate<’2005-12-1’

   

9. 很多时候用 exists 代替 in 是一个好的选择:

#例如:
select num from a where num in(select num from b)
#优化:
select num from a where exists(select 1 from b where num=a.num)


10. 任何地方都不要使用 `select * from t` ,用具体的字段列表代替`*`,不要返回用不到的任何字段  


## 其他补充:

1. **并不是所有索引对查询都有效**
SQL是根据表中数据来进行查询优化的,当索引列有大量数据重复时,SQL查询可能不会去利用索引

2. **索引并不是越多越好**
索引固然可以提高相应的`select`的效率,但同时也降低了`insert`及`update`的效率,因为`insert`或`update`时有可能会重建索引,所以怎样建索引需要慎重考虑,视具体情况而定。一个表的索引数最好不要超过`6`个,若太多则应考虑一些不常使用到的列上建的索引是否有必要

3. **不要在 `where` 子句中的`=`左边进行函数、算术运算或其他表达式运算**
否则系统将可能无法正确使用索引
   

4. **使用复合索引注意**   
必须使用到该索引中的第一个字段作为条件时才能保证系统使用该索引,否则该索引将不会被使用,并且应尽可能的让字段顺序与索引顺序相一致