Sql-Server
SQL Server 昂貴的嵌套循環連接和惰性表假離線
我正在嘗試調整以下查詢,無論作為參數傳入什麼值,都需要 15-16 秒,查詢是:
select distinct d.documentpath as path, d.documentname as name, d.datecreated as created, pc.DateProcessed from datagatheringruntime dgr inner join processentitymapping pem on pem.entityid = dgr.entityid inner join document d on d.entityid = pem.entityid or d.unitofworkid = pem.processid left join PendingCorrespondence pc on pc.PendingCorrespondenceId = d.PendingCorrespondenceId where rootid = @P0 and dgr.name in('cust_pn', 'case_pn') OPTION(RECOMPILE)
我已經更新了查詢所涉及的所有表的統計資訊(不包括
DataGatheringRuntime
在 ~ 處很大的表100GB
),並嘗試使用 a 重構查詢,CTE
但獲得了相同的執行計劃並需要一些幫助。實際的執行計劃可以在這裡找到:
https://www.brentozar.com/pastetheplan/?id=ByUVIqlFE
從執行計劃中可以清楚地看出,問題出在表上的非聚集索引之後的外部輸入上
nested loop join
,但我不知道如何解決這個問題,希望得到任何指導。lazy table spool``scan``IX_Camunda_1``Document
我會嘗試刪除和
OR
之間的連接中的子句document``processingentitymapping
你可以這樣做
UNION
SELECT distinct d.documentpath as path, d.documentname as name, d.datecreated as created, pc.DateProcessed FROM datagatheringruntime dgr INNER JOIN processentitymapping pem on pem.entityid = dgr.entityid INNER JOIN document d on d.entityid = pem.entityid LEFT JOIN PendingCorrespondence pc on pc.PendingCorrespondenceId = d.PendingCorrespondenceId WHERE rootid = @P0 and dgr.name in('cust_pn', 'case_pn') UNION SELECT distinct d.documentpath as path, d.documentname as name, d.datecreated as created, pc.DateProcessed FROM datagatheringruntime dgr INNER JOIN processentitymapping pem on pem.entityid = dgr.entityid INNER JOIN document d on d.unitofworkid = pem.processid LEFT JOIN PendingCorrespondence pc on pc.PendingCorrespondenceId = d.PendingCorrespondenceId WHERE rootid = @P0 and dgr.name in('cust_pn', 'case_pn') OPTION(RECOMPILE);
過濾掉,直到我們剩下 9 行。
將 更改
OR
為 aUNION
應該刪除線軸,您可能需要在刪除OR
.重寫後可以提高性能的索引
UNION
CREATE INDEX IX_EntityId on document(EntityId) INCLUDE(DocumentPath, DocumentName, DateCreated, PendingCorrespondenceId); CREATE INDEX IX_UnitOfWorkId on document(UnitOfWorkId) INCLUDE(DocumentPath, DocumentName, DateCreated, PendingCorrespondenceId);
有關此問題的另一個範例,請參見此處