我有下面的T-SQL查询(由
linq-to-sql生成,所以看起来有点奇怪.)当我删除前10名时,它在1秒内运行.当我离开前10名时,需要68秒.
没有前10名,总行数仅为19.
为什么前10名在这种情况下会破坏性能如此之高?
SELECT TOP (10) [t3].[value] AS [StartDate], [t3].[AH_TimeStamp4] AS [EndDate], [t3].[value2] AS [RunTime], [t3].[AH_Idnr] AS [RunNumber], [t3].[AH_Status] AS [StatusCode], [t3].[STATUS_DESC] AS [StatusDesc], [t3].[STATUS_TYPE] AS [StatusType]
FROM (
SELECT COALESCE([t1].[AH_TimeStamp2],[t1].[AH_TimeStamp1]) AS [value], [t1].[AH_TimeStamp4], CONVERT(BigInt,(((CONVERT(BigInt,DATEDIFF(DAY, [t1].[AH_TimeStamp1], [t1].[AH_TimeStamp4]))) * 86400000) + DATEDIFF(MILLISECOND, DATEADD(DAY, DATEDIFF(DAY, [t1].[AH_TimeStamp1], [t1].[AH_TimeStamp4]), [t1].[AH_TimeStamp1]), [t1].[AH_TimeStamp4])) * 10000) AS [value2], [t1].[AH_Idnr], [t1].[AH_Status], [t2].[STATUS_DESC], [t2].[STATUS_TYPE], [t0].[OH_Name]
FROM [dbo].[OH] AS [t0]
INNER JOIN [dbo].[AH] AS [t1] ON ([t0].[OH_Idnr]) = [t1].[AH_OH_Idnr]
INNER JOIN [dbo].[CHK_JOB_STATUS_CODE] AS [t2] ON [t1].[AH_Status] = ([t2].[STATUS_CODE])
) AS [t3]
WHERE [t3].[OH_Name] = @p0
ORDER BY [t3].[AH_Idnr] DESC
编辑 – >根据要求,这是没有Take(10)的linq生成的查询
SELECT [t3].[value] AS [StartDate], [t3].[AH_TimeStamp4] AS [EndDate], [t3].[value2] AS [RunTime], [t3].[AH_Idnr] AS [RunNumber], [t3].[AH_Status] AS [StatusCode], [t3].[STATUS_DESC] AS [StatusDesc], [t3].[STATUS_TYPE] AS [StatusType]
FROM (
SELECT COALESCE([t1].[AH_TimeStamp2],[t1].[AH_TimeStamp1]) AS [value], [t1].[AH_TimeStamp4], CONVERT(BigInt,(((CONVERT(BigInt,DATEDIFF(DAY, [t1].[AH_TimeStamp1], [t1].[AH_TimeStamp4]))) * 86400000) + DATEDIFF(MILLISECOND, DATEADD(DAY, DATEDIFF(DAY, [t1].[AH_TimeStamp1], [t1].[AH_TimeStamp4]), [t1].[AH_TimeStamp1]), [t1].[AH_TimeStamp4])) * 10000) AS [value2], [t1].[AH_Idnr], [t1].[AH_Status], [t2].[STATUS_DESC], [t2].[STATUS_TYPE], [t0].[OH_Name]
FROM [dbo].[OH] AS [t0]
INNER JOIN [dbo].[AH] AS [t1] ON ([t0].[OH_Idnr]) = [t1].[AH_OH_Idnr]
INNER JOIN [dbo].[CHK_JOB_STATUS_CODE] AS [t2] ON [t1].[AH_Status] = ([t2].[STATUS_CODE])
) AS [t3]
WHERE [t3].[OH_Name] = @p0
ORDER BY [t3].[AH_Idnr] DESC
编辑2 – >这是LINQ查询 – 没什么特别的,只有3个连接
List<UC4Status> statusList = uc4DB.OHs.Where(o => o.OH_Name == jobName).Join(uc4DB.AHs, oh => oh.OH_Idnr, ah => ah.AH_OH_Idnr, (oh, ah) => ah)
.Join(uc4DB.CHK_JOB_STATUS_CODEs, ah => ah.AH_Status, job => job.STATUS_CODE, (a, s) =>
new UC4Status
{
StartDate = a.AH_TimeStamp2 ?? a.AH_TimeStamp1,
EndDate = a.AH_TimeStamp4,
RunTime = a.AH_TimeStamp4 - a.AH_TimeStamp1,
StatusType = s.STATUS_TYPE,
StatusDesc = s.STATUS_DESC,
StatusCode = a.AH_Status,
RunNumber = a.AH_Idnr
}).OrderByDescending(r => r.RunNumber).Take(maxResults).ToList();
最佳答案 返回的行数比连接的每个表中的行数更重要.如果不访问查询计划,很难说问题是什么.但是,问题可能是由于过时或缺少列统计信息以及缺少良好的索引导致查询优化器在使用top时做出非常糟糕的决定.例如,如果优化器错误地假设top语句只对每个连接表中的少量行进行操作,那么它可以选择在每个连接表上使用内部循环连接和表扫描 – 这可能是一个非常可怕的对大量记录进行慢速操作(但只使用少量记录时可以非常有效地工作).在没有top的情况下,优化器可以正确地假设它必须扫描连接表中的大量记录并使用更适合这种操作的方法,例如来自表扫描的散列匹配连接.
您可以尝试更新统计信息并添加其他索引以查看是否有帮助.