SQL语句优化


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

以下写法会造成全表的扫描,例如:

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

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 datediff(day,datefield,'2017-05-17') >= 0

上面两句都对字段进行了函数处理,会导致查询分析器放弃了索引的使用。

正确的写法:

select id from userinfo where name like'xiaomi%'

select id from userinfo where datefield <= '2017-05-17'

通俗理解就是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)

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

select id from userinfo where name is null

尽量在数据库字段中不出现null,如果查询的时候条件为 is null ,索引将不会被使用,造成查询效率低,

因此数据库在设计的时候,尽可能将某个字段可能为空的时候设置默认值,那么查询的时候可以

根据默认值进行查询,比如name字段设置为0,查询语句可以修改为

select id from userinfo where name=0

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

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

而对于 < 、 <= 、 = 、 > 、 >= 、 BETWEEN AND,数据库才会使用索引。

因此对于上面的查询,正确写法可以改为:

select name from userinfo where id < 0 union all

select name from userinfo where id > 0

7、少用in 或 not in

对于连续的数值范围查询尽量使用BETWEEN AND,例如:

select name from userinfo where id BETWEEN  10 AND 70

 上一篇
k8s资源监控 k8s资源监控
k8s 资源监控 kubernetes新一代的监控模型由:核心指标流水线和第三方非核心监控流水线组成。核心指标流水线由kubelet、 metric-server 以及由API-server提供的API组成;负责CPU累积使用率、内存实时使
2020-11-14
下一篇 
Prometheus Prometheus
Prometheus架构介绍介绍 1.一套开源的系统监控报警框架。 Prometheus基于Golang编写,不存在任何的第三方依赖。 由 SoundCloud 开源监控告警解决方案。 单一节点就可以存储百万的监控指标,每秒处理数十万
2020-10-29
  目录