平臺:SQL Server 2012的爲什麼這個指標並不能提高查詢性能
背景:我有兩個相當大的日誌表 - 600K左右記錄每個正在使用PK/FK加入。爲了爭論起見,我們稱它們爲ReallyBigLog1和ReallyBigLog2。查詢(下面)大約需要3.5秒才能運行。 WHERE子句包含三個不同的值。當被要求幫助改進此查詢時,我立即注意到WHERE子句中的項目未被編入索引。我躊躇滿志地建議添加索引 - 假設提高的性能會讓我看起來像英雄。但是,額外的指數沒有可衡量的影響。
問題:給定下面的查詢,爲什麼索引StartTime,EndTime和DateStamp對查詢時間沒有可測量的影響?
查詢
SELECT
IrreleventField1,
IrreleventField2,
IrreleventField3....
FROM [dbo].[ReallyBigLog1] AS [T1]
INNER JOIN [dbo].[ReallyBigLog2] AS [T2] ON [T1].[Id] = [T2].[Id]
WHERE ([T1].[EndTime] IS NOT NULL) AND ([T1].[StartTime] IS NOT NULL) AND ([T2].[DateStamp] >= '2017-5-16 00:00:00')
指標
CREATE NONCLUSTERED INDEX [ix_RecommendedIndex]
ON [dbo].[ReallyBigLog1]
([StartTime] , [EndTime])
CREATE NONCLUSTERED INDEX [IX_DateStamp]
ON [dbo].[ReallyBigLog2]
([DateStamp])
執行計劃
5 SELECT
4 Compute Scalar
3 Merge Join/Inner Join Merge:([dbo].[ReallyBigLog1].[Id] [T2]=[dbo].[ReallyBigLog1].[Id] [T1]), Residual:([dbo].[ReallyBigLog2].[Id] as [T2].[Id]=[dbo].[ReallyBigLog1].[Id] as [T1].[Id])
1 Clustered Index Scan Predicate:([dbo].[ReallyBigLog1].[StartTime] as [T1].[StartTime] IS NOT NULL AND [dbo].[ReallyBigLog1].[EndTime] as [T1].[EndTime] IS NOT NULL), ORDERED FORWARD [dbo].[ReallyBigLog1].[PK_dbo.ReallyBigLog1] [T1]
2 Clustered Index Scan Predicate:([dbo].[ReallyBigLog2].[DateStamp] as [T2].[DateStamp]>='2017-05-16 00:00:00.000'), ORDERED FORWARD [dbo].[ReallyBigLog2].[PK_dbo.ReallyBigLog2] [T2]
編輯(表組成)
SELECT
(SELECT COUNT(*) FROM ReallyBigLog1 WHERE StartTime IS NULL) as NullStartTime,
(SELECT COUNT(*) FROM ReallyBigLog1 WHERE EndTime IS NULL) as NullEndTime,
(SELECT COUNT(*) FROM ReallyBigLog1) as Log1Count,
(SELECT COUNT(*) FROM ReallyBigLog2 WHERE DateStamp > '2017-5-16 00:00:00') AS DateStampUsage,
(SELECT COUNT(*) FROM ReallyBigLog2) AS Log2Count
DateStampUsage Log2Count NullStartTime NullEndTime Log1Count
443038 651929 33748 34144 509545
優化器最有可能估計掃描表更便宜,特別是因爲合併連接需要數據進行排序。多少數據與'DateStamp> ='2017-5-16''這個標準相符?這些時間中有多少時間爲零? –
謝謝James,我將該信息添加爲該問題的編輯。 – SteveJ
看着你的執行計劃,它看起來像SQL服務器,根本沒有使用新的索引,因此它沒有改進任何..因爲你在這裏提供的有限的數據,我們沒有什麼可以明確地指定,說這篇文章可能會幫助你一下https://www.simple-talk.com/sql/performance/identifying-and-solving-index-scan-problems/。 – Surendra