常见的SQL优化
发表于|更新于|技术博客
|总字数:799|阅读时长:2分钟|浏览量:
Mysql的SQL优化关键字
Explain
常见SQL优化规则
- 查询优化,尽量避免全表扫描.考虑
where
及group by
建议索引 - 避免在
where
的语句中使用!=
或<>
操作符,否则引擎将放弃索引进行全表扫描 - 避免在
where
的语句中进行null
值判断,否则引擎将放弃索引进行全表扫描#例如:
select id from t where num is null - 避免在
where
的语句中使用or
来连接条件,否则引擎将放弃索引进行全表扫描
#例如: |
- 避免在
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
|
#例如:
select id from t where num/2=100
#优化:
select id from t where num=100*2
|
#例如:
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’
|
#例如:
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. **使用复合索引注意**
必须使用到该索引中的第一个字段作为条件时才能保证系统使用该索引,否则该索引将不会被使用,并且应尽可能的让字段顺序与索引顺序相一致
文章作者: MUMU
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来源 blog.wo0ow.com!