sql大數據多條件查詢索引優化


此優化的前提可以稱之為最近流行的頭條人物“許三多”,總數據多,查詢條件多,返回列多

優化前分頁查詢內部select列為需要的全部列,優化后內部select只返回ID主鍵,外部查詢關聯原數據表,然后查出所需要的列

 

例子1

優化前:

 

  1. select t.* from (  
  2.         select r.* ,row_number() over(order by r.id desc) row from tab(nolock) r   
  3.         where 1=1 and r.IsDelete=0 and r.Status>0 and r.PlatformID=1 and r.CreateUser=100000       
  4. 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

 

優化后:

 

  1. select r.* from (  
  2.         select r.ID ,row_number() over(order by r.id desc) row from tab(nolock) r   
  3.         where 1=1 and r.IsDelete=0 and r.Status>0 and r.PlatformID=1 and r.CreateUser=100000       
  4. 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秒多

 

  1. select * from (  
  2.         select d.LessonPlanID,d.ResUrl,p.createID,p.CreateTime,row_number() over(order by d.id desc) row  
  3.         from tablA(nolock) d   
  4.         join tablB(nolock) p on p.id=d.lessonplanid  
  5.         where p.createID in(109486,103295,103298,109347,130346,181382,330312)  
  6.     ) 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毫秒

 

  1. select d.LessonPlanID,d.ResUrl,p.createID,p.CreateTime from (  
  2.         select  d.id,row_number() over(order by d.id desc) row  
  3.         from tablA(nolock) d   
  4.         join tablB(nolock) p on p.id=d.lessonplanid  
  5.         where p.createID in(109486,103295,103298,109347,130346,181382,330312)  
  6. ) t join tablA(nolock) d on d.id=t.id   join tablB(nolock) p on p.id=d.lessonplanid  
  7.  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 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM