请简单说明SQL语句书可以提高执行效率的5种需要注意的书写方法

解决方案 »

  1.   

    where col like '%aaa' --不要用
      

  2.   

    能用exists和not exists,就不要用in 和not in
      

  3.   

    能用exists和not exists,就不要用in 和not in
    IT1129(修理地球)
    ------------------------------------------
    我恰恰习惯相反
    能说一下为什么吗?
      

  4.   

    exists和not exists
    着重考虑的是是否有返回行而不是值
    in 和 not in 是和返回的值对比 匹配
    还有其他的含义吗?
      

  5.   

    表A   和    表B
    如果表A是个大表
        表B是个小表
    select * from 表A where id in (select id from 表B)
    方法速度快过
    select * from 表A where exists(select 1 from 表B where 表A.id=表B.id)
    ------------to: wolf5200() ( ) 信誉:100    Blog   加为好友  2007-07-12 18:11:29  得分: 0  
     
     
       能用exists和not exists,就不要用in 和not in
    IT1129(修理地球)
    ------------------------------------------
      讨论IN和EXISTS。
        select * from t1 where x in ( select y from t2 )
        事实上可以理解为:
        select * 
          from t1, ( select distinct y from t2 ) t2
         where t1.x = t2.y;
        ——如果你有一定的SQL优化经验,从这句很自然的可以想到t2绝对不能是个大表,因为需要对t2进行全表的“唯一排序”,如果t2很大这个排序的性能是不可忍受的。但是t1可以很大,为什么呢?最通俗的理解就是因为t1.x=t2.y可以走索引。但这并不是一个很好的解释。试想,如果t1.x和t2.y都有索引,我们知道索引是种有序的结构,因此t1和t2之间最佳的方案是走merge join。另外,如果t2.y上有索引,对t2的排序性能也有很大提高。
        select * from t1 where exists ( select null from t2 where y = x )
        可以理解为:
        for x in ( select * from t1 )
        loop
           if ( exists ( select null from t2 where y = x.x )
           then 
              OUTPUT THE RECORD!
           end if
        end loop
        ——这个更容易理解,t1永远是个表扫描!因此t1绝对不能是个大表,而t2可以很大,因为y=x.x可以走t2.y的索引。
        综合以上对IN/EXISTS的讨论,我们可以得出一个基本通用的结论:IN适合于外表大而内表小的情况;EXISTS适合于外表小而内表大的情况。
        如果你对上述说法表示怀疑,请看以下测试: