zoukankan      html  css  js  c++  java
  • 常用SQL优化技巧

    作为程序员经常和数据库打交道的时候还是非常频繁的,掌握住一些Sql的优化技巧还是非常有必要的。下面列出一些常用的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)

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

    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

    以上只是相对来说比较常用的sql优化技巧,当然还有很多欢迎补充!

  • 相关阅读:
    WAF绕过方法
    ”非常危险“的Linux命令
    CSRF--花式绕过Referer技巧
    安卓手机的后门控制工具SPADE
    基于RedHat发行的Apache Tomcat本地提权漏洞
    SQL注入--宽字节注入
    MySQL提权
    CF1067D. Computer Game(斜率优化+倍增+矩阵乘法)
    CF1063F. String Journey(后缀数组+线段树)
    BZOJ4732. [清华集训2016]数据交互(树链剖分+线段树+multiset)
  • 原文地址:https://www.cnblogs.com/mm962464/p/13063714.html
Copyright © 2011-2022 走看看