当前位置:Gxlcms > 数据库问题 > SQL Server 使用分区函数实现查询优化

SQL Server 使用分区函数实现查询优化

时间:2021-07-01 10:21:17 帮助过:22人阅读

T_UserCollectMerchant.CollectID,T_UserCollectMerchant.MerchantID,T_UserCollectMerchant.UserID,T_UserCollectMerchant.AddTime, (select top 1 LastUpdate from T_GoodsInfo where MerchantID=T_UserCollectMerchant.MerchantID order by LastUpdate desc) as LastNewTime from T_UserCollectMerchant where UserID=19 order by CollectID desc offset 0 row fetch next 40 rows only

但是,当商品数据达到百万级后,这一句代码的执行效率就变得惨不忍睹,经常卡死,

技术分享

再看看执行计划

技术分享

商品表的扫描几乎占据了所有cpu资源

于是乎,查询商家最后更新时间的方式必须要优化了

新建了一个视图,内容如下

SELECT * FROM      (SELECT   LastUpdate, MerchantID, (ROW_NUMBER() OVER (PARTITION BY MerchantID ORDER BY LastUpdate DESC)) AS rowid
            FROM  T_GoodsInfo
            ) AS T WHERE T .rowid < 2

按照商家ID将商品数据分组,并取出最新一条数据的时间

然后将SQL 查询语句更新为:

select T_UserCollectMerchant.CollectID,T_UserCollectMerchant.MerchantID,T_UserCollectMerchant.UserID,
        LastUpdate as LastNewTime    
from T_UserCollectMerchant 
left join V_GoodsInfo_MerchantCount on V_GoodsInfo_MerchantCount.MerchantID=T_UserCollectMerchant.MerchantID
where userid=19
order by CollectID desc offset 0 row fetch next 40 rows only

重新执行

技术分享

效率大大提高了

 技术分享

从执行计划看,还可以继续优化,时间关系,暂时到这里

 

SQL Server 使用分区函数实现查询优化

标签:log   pre   函数实现   ast   ext   collect   简单   nbsp   blog   

人气教程排行