zoukankan      html  css  js  c++  java
  • sql优化的几种方法

    sql优化的几种方法

    1. 查询的时候避免全表扫描,在经常会where和order by的列上建立索引
    2. 尽量避免在where里对字段进行null值判断,否则的话会让数据库引擎放弃索引而进行全表扫描,如
      select id from students where num is null
      -- 尽量避免(num is null)这种的查询

      可以在num列上设置默认值0,确保num列上没有null值,然后可以这样查询

      select id from students where num=0
    3. 避免在where语句里使用!=,<,>等操作符,否则的话会让数据库引擎放弃索引而进行全表扫描
    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 students where num in(1,2,3)
      
      -- 对于连续的数值,能用 between 就不要用 in 了:    
      select id from students where num between 1 and 3
    6. 使用通配符的时候,不要在前面加%,否则的话会不走索引直接全表扫描,如
      select id from t where name like '%abc%'
    7. 避免在where语句中对字段进行表达式操作,否则的话会不走索引直接全表扫描。还有不要在where语句的=左边做函数、算数运算、表达式运算,,否则的话会不走索引直接全表扫描。如
      select id from t where num/2=100
      
      -- 应改为:    
      select id from t where num=100*2
    8. 在使用索引字段作为条件时,如果该索引是符合索引,那么必须使用到该索引的第一个字段作为条件时才能保证系统使用该索引,否则该索引将不会被使用,并且应该尽可能的让字段顺序与索引顺序一致。
    9. 不要使用select * from t, 应该用具体的字段代替*,用到什么字段就查什么字段
    10. 很多时候用 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)
  • 相关阅读:
    SqlServer2008 安装经验日志总结
    Moile手机开发日志总结若干问题
    安装和卸载Android应用程序(apk包)
    Android Intent 常见用法总结
    vs2008+sqlserver2008 同一台服务器webconfig 数据连接串的配置要点
    注意了android日期控件月份比实际少一个月
    Android 蓝牙开发研究
    [javascript] 怎样在javascript里面调试object
    [Ubuntu] 转载:ubuntu apache2配置
    [Ubuntu] 如何在Ubuntu11.04将PHP5.3降级到PHP5.2
  • 原文地址:https://www.cnblogs.com/blog-rui/p/10894608.html
Copyright © 2011-2022 走看看