幫忙改一下這個簡單的排序能否快一點 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
------解决方案--------------------