SQL优化简单总结

SQL优化简单总结

  • 查询优化
    1. 避免全表扫描,优先考虑在where和order by涉及的列上建立索引

    2. is null值判断会导致引擎放弃使用索引,变成全表扫描,如:

    select id from t where num is null
    -- 导致全表扫描
    
    1. !=或<>操作符也会导致引擎放弃使用索引,进行全表扫描,如:
    select id from t where num <> 0
    -- 导致全表扫描
    
    1. or在条件不都有索引的情况下,导致放弃使用索引进行全表扫描,如:
    select id from t where num=10 or Name = 'admin'
    

    可以改成这样查询

    select id from t where num = 10
    union all
    select id from t where Name = 'admin'
    
    1. in和not in会导致全表扫描,用exists代替in,如:
    select id from t where num in(1,2,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)
    
    1. like查询前置%会导致全表查询,如
    select id from t where name like%abc%
    1. where中的字段运算操作会导致全表扫描,如:
    select id from t where num/2 = 100
    

    应改为

    select id from t where num = 100*2
    
    1. where中的字段进行函数操作会导致不走索引进行全表扫描,如:
    select id from t where substring(name,1,3) = ’abc’
    

    应改为:

    select id from t where name like 'abc%'
    

    总结7,8,为where语句中的字段**=**左边进行函数,算数或其他表达式,引擎将不走索引,进行全表查询

  • 大数据量操作优化

实际案例分析:拆分大的 DELETE 或INSERT 语句,批量提交SQL语句

如果你有一个大的处理,你一定把其拆分,使用 LIMIT oracle(rownum),sqlserver(top)条件是一个好的方法。下面是一个mysql示例:

while(1){

   //每次只做1000条

   mysql_query(“delete from logs where log_date <= ’2012-11-01’ limit 1000”);

   if(mysql_affected_rows() == 0){

     //删除完成,退出!
     break;
  }

//每次暂停一段时间,释放表让其他进程/线程访问。
usleep(50000)

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值