1.对查询进行优化,应尽量防止全表扫描,首先应考虑在 where 及 order by 触及的列上树立索引。
2.应尽量防止在 where 子句中对字段进行 null 值判别,否则将导致引擎抛弃运用索引而进行全表扫描,如:
select id from t where num is null
能够在num上设置默认值0,保证表中num列没有null值(这也是为什么一般需要给字段设默认值0或许空字符串的原因),然后这样查询:
select id from t where num=0
3.应尽量防止在 where 子句中运用!=、<>、!>、!<、not操作符,否则将引擎抛弃运用索引而进行全表扫描。
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
5.in 和 not in 也要慎用,在运用不当的情况下会导致全表扫描,如:
select id from t where num in(1,2,3)
关于接连的数值,能用 between 就不要用 in 了:
select id from t where num between 1 and 3
许多时分用 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)
6.下面的含糊查询也将导致全表扫描:
select id from t where name like ‘%abc%’
select id from t where name like ‘%abc’
可是下面的这种含糊查询仍然能够运用索引
select id from t where name like ‘abc%’
7.应尽量防止在 where 子句中对字段的“=”左面进行函数、算术运算或其他表达式运算,这将导致引擎抛弃运用索引而进行全表扫描。
如:
select id from t where num/2=100
应改为:
select id from t where num=100*2
又如查找name以abc最初的id:
select id from t where substring(name,1,3)=‘abc’
应改为:
select id from t where name like ‘abc%’
8.不要运用 select * from table ,用详细的字段列表替代“*”,不要回来用不到的任何字段。
9.不要运用 select count() from table,这样不带任何条件的count会引起全表扫描,而且没有任何事务含义,count()能够用count(1)替代,但在我的5.7.22版别的mysql中count(*)和count(1)运转速度相同。
10.留意:关于非常复杂的sql,有些人习气对其树立视图,然后在视图的基础上进行查询。尽管这样sql写的简略了许多,可是并不会进步查询功率,由于该履行的sql仍是得履行。
能够在视图中树立索引来进步查询功率,但会添加数据改变(增修改)的开支。
11.索引最左前缀准则
在运用索引进步查询速度时要留意遵从最左前缀准则,比方有个组合索引index(c1,c2,c3),这其实是相当于别离树立了三组索引:c1、c1,c2、c1,c2,c3。
所以当where后边的条件是c1='1’或许c1=‘1’ and c2='2’或许c1=‘1’ and c2=‘2’ and c3='3’都能够走索引,而c2='2’或许c3='3’或许c2=‘2’ and c3='3’则不能走索引。
别的比如c2=‘2’ and c1=‘1’ and c3='3’之类的查询条件,看似不满足最左前缀准则,但由于这和c1=‘1’ and c2=‘2’ and c3='3’是等效的,mysql优化器会主动优化成能够走索引的方式。