SQL Server 使用分區函數實現查詢最佳化

來源:互聯網
上載者:User

標籤: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 使用分區函數實現查詢最佳化

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.