軟件是對質量的不懈追求

          exists真的就比in的效率高嗎?

          系統要求進行SQL優化,對效率比較低的SQL進行優化,使其運行效率更高,其中要求對SQL中的部分in/not in修改為exists/not exists

          修改方法如下:

          in的SQL語句

          SELECT id, category_id, htmlfile, title, convert(varchar(20),begintime,112) as pubtime
          FROM tab_oa_pub WHERE is_check=1 and
          category_id in (select id from tab_oa_pub_cate where no='1')
          order by begintime desc

          修改為exists的SQL語句
          SELECT id, category_id, htmlfile, title, convert(varchar(20),begintime,112) as pubtime
          FROM tab_oa_pub WHERE is_check=1 and
          exists (select id from tab_oa_pub_cate where tab_oa_pub.category_id=convert(int,no) and no='1')
          order by begintime desc

          分析一下exists真的就比in的效率高嗎?

               我們先討論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適合于外表小而內表大的情況。

          我們要根據實際的情況做相應的優化,不能絕對的說誰的效率高誰的效率低,所有的事都是相對的

          not in 和not exists
          如果查詢語句使用了not in 那么內外表都進行全表掃描,沒有用到索引;
          而not extsts 的子查詢依然能用到表上的索引。
          所以無論那個表大,用not exists都比not in要快。

          原文:http://blog.csdn.net/jwisdom/archive/2007/09/27/1803577.aspx

          posted on 2009-11-03 09:48 BlakeSu 閱讀(296) 評論(0)  編輯  收藏


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 新竹县| 承德县| 清徐县| 峨山| 大化| 通榆县| 临沧市| 颍上县| 无极县| 南靖县| 太康县| 元谋县| 疏附县| 克什克腾旗| 富顺县| 马龙县| 贵阳市| 保靖县| 南康市| 克什克腾旗| 循化| 清原| 肇庆市| 肇东市| 乌苏市| 佛山市| 穆棱市| 西和县| 鄱阳县| 宁河县| 阿坝县| 通州区| 玉林市| 富阳市| 什邡市| 靖边县| 佛教| 衡水市| 英超| 碌曲县| 宜君县|