標籤:log pre 函數實現 ast ext collect 簡單 nbsp blog
在項目中遇到一個需求,需要在商家收藏資訊中,擷取到該商家發布的最新一條商品的發布時間,需求很簡單,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=19order 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 TWHERE 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.MerchantIDwhere userid=19order by CollectID desc offset 0 row fetch next 40 rows only
重新執行
效率大大提高了
從執行計畫看,還可以繼續最佳化,時間關係,暫時到這裡
SQL Server 使用分區函數實現查詢最佳化