SQL Server 使用分区函数实现查询优化
在项目中遇到一个需求,需要在商家收藏信息中,获取到该商家发布的最新一条商品的发布时间,需求很简单,SQL语句也不复杂,
select 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
重新执行
效率大大提高了
从执行计划看,还可以继续优化,时间关系,暂时到这里