日期:2014-05-17  浏览次数:20576 次

幫忙改一下這個簡單的排序能否快一點
select top 1000 id,username,usercode,isnull (dCompDt,convert(smalldatetime,'2078-06-06')) as newCompDt from tablename order by get_newCompDt desc 
==========================
dCompDt是完成時間,已完成的(有時間)排在後面用倒序排,沒完成的排在前面(都是null值),
用上面的newCompDt方式來排好慢啊,運行要8秒左右,數據有30萬條記錄,已經top 1000了啊。
請問可以改成什麼樣的寫法會更快?

------解决方案--------------------
你都没where语句,当然慢拉,全表扫描的。把get_newCompDt做个降序的聚集索引,可以减少order by 的开销。
------解决方案--------------------
select top 1000 id,username,usercode
from tablename 
 order by case when dCompDt=null then 0 else 1 end,dCompDt desc
------解决方案--------------------
select top 1000 id,username,usercode,isnull (dCompDt,convert(smalldatetime,'2078-06-06')) as newCompDt from tablename order by 
case when dCompDt is null then 0 else 1 end ,dCompDt desc
------解决方案--------------------
id 主键+dCompDt 索引

语句改成 
SQL code
select top 1000 id,username,usercode,isnull (dCompDt,convert(smalldatetime,'2078-06-06')) as newCompDt from tablename
case when dCompDt is  null then 0 else 1 end,dCompDt desc

------解决方案--------------------
探讨

引用:
引用:

不用索引的情況下怎麼寫會好一點呢?因為我沒權限改數據庫


刚没看到,你没权利动数据那你优化?


我的sql是寫在網頁裡的,數據庫我動不了