此優化的前提可以稱之為最近流行的頭條人物“許三多”,總數據多,查詢條件多,返回列多
優化前分頁查詢內部select列為需要的全部列,優化后內部select只返回ID主鍵,外部查詢關聯原數據表,然后查出所需要的列
例子1
優化前:
- select t.* from (
- select r.* ,row_number() over(order by r.id desc) row from tab(nolock) r
- where 1=1 and r.IsDelete=0 and r.Status>0 and r.PlatformID=1 and r.CreateUser=100000
- ) as t where row between 1 and 10
select t.* from ( select r.* ,row_number() over(order by r.id desc) row from tab(nolock) r where 1=1 and r.IsDelete=0 and r.Status>0 and r.PlatformID=1 and r.CreateUser=100000 ) as t where row between 1 and 10
優化后:
- select r.* from (
- select r.ID ,row_number() over(order by r.id desc) row from tab(nolock) r
- where 1=1 and r.IsDelete=0 and r.Status>0 and r.PlatformID=1 and r.CreateUser=100000
- ) as t join tab r on r.id=t.id where row between 1 and 10
select r.* from ( select r.ID ,row_number() over(order by r.id desc) row from tab(nolock) r where 1=1 and r.IsDelete=0 and r.Status>0 and r.PlatformID=1 and r.CreateUser=100000 ) as t join tab r on r.id=t.id where row between 1 and 10
最近又有一個例子
例子2
優化前:tablA數據量1千多萬,tablB數據量幾百萬,查詢速度11秒多
- select * from (
- select d.LessonPlanID,d.ResUrl,p.createID,p.CreateTime,row_number() over(order by d.id desc) row
- from tablA(nolock) d
- join tablB(nolock) p on p.id=d.lessonplanid
- where p.createID in(109486,103295,103298,109347,130346,181382,330312)
- ) t where t.row between 1 and 20
select * from ( select d.LessonPlanID,d.ResUrl,p.createID,p.CreateTime,row_number() over(order by d.id desc) row from tablA(nolock) d join tablB(nolock) p on p.id=d.lessonplanid where p.createID in(109486,103295,103298,109347,130346,181382,330312) ) t where t.row between 1 and 20
優化后:查詢速度14毫秒
- select d.LessonPlanID,d.ResUrl,p.createID,p.CreateTime from (
- select d.id,row_number() over(order by d.id desc) row
- from tablA(nolock) d
- join tablB(nolock) p on p.id=d.lessonplanid
- where p.createID in(109486,103295,103298,109347,130346,181382,330312)
- ) t join tablA(nolock) d on d.id=t.id join tablB(nolock) p on p.id=d.lessonplanid
- where t.row between 1 and 20
select d.LessonPlanID,d.ResUrl,p.createID,p.CreateTime from ( select d.id,row_number() over(order by d.id desc) row from tablA(nolock) d join tablB(nolock) p on p.id=d.lessonplanid where p.createID in(109486,103295,103298,109347,130346,181382,330312) ) t join tablA(nolock) d on d.id=t.id join tablB(nolock) p on p.id=d.lessonplanid where t.row between 1 and 20