Mysql查询优化

sql语句的处理过程:

Mysql查询优化

常见的SQL优化技巧:

1、注意通配符中的Like的使用:

 select id,name from userinfo where name like '%name'

 通配符%在前会造成全表的扫描

 应当将它改造成:

 select id,name from userinfo where name like 'name%'

 这样在执行时效率将加快,因为使用了索引。

2、不要在where子句中对字段进行函数操作

比如:

select id from userinfo where substring(name,1,6) = 'xiaomi'

函数的处理会使查询分析器放弃对索引的使用

改成:

select id from userinfo where name like'xiaomi%'

也就是说where子句“=”左边不要出现函数、算数运算或者其他表达式运算。

3、在子查询中,尽量用exists代替in。

select name from userinfo a where id in(select id from userinfo b)

可以改为

select name from userinfo a where exists(select 1 from userinfo b where id = a.id)

下面的查询速度比in查询的要快很多。

4、where子句中尽量不要使用is null或is not null对字段进行判断

这两个操作不会用到索引,因此在数据库设计时尽可能在某个字段为空时设置默认值。

5、避免在where子句中使用or作为链接条件

例如:select id from userinfo where name='xiaoming' or name='xiaowang'

可以改写为:

select id from userinfo where name = 'xiaoming' union all

select id from userinfo where name = 'xiaowang'

6、避免在where子句中使用!=或<>操作符

数据库在查询时,对 != 或 <> 操作符不会使用索引

可以改为:

select name from userinfo where id < 0 union all

select name from userinfo where id > 0

7、少用in 或 not in