小编Cho*_*man的帖子

非常相似的查询,截然不同的性能

我有两个非常相似的查询

第一个查询:

SELECT count(*)
FROM Audits a
    JOIN AuditRelatedIds ari ON a.Id = ari.AuditId
WHERE 
    ari.RelatedId = '1DD87CF1-286B-409A-8C60-3FFEC394FDB1'
    and a.TargetTypeId IN 
    (1,2,3,4,5,6,7,8,9,
    11,12,13,14,15,16,17,18,19,
    21,22,23,24,25,26,27,28,29,30,
    31,32,33,34,35,36,37,38,39,
    41,42,43,44,45,46,47,48,49,
    51,52,53,54,55,56,57,58,59,
    61,62,63,64,65,66,67,68,69,
    71,72,73,74,75,76,77,78,79)
Run Code Online (Sandbox Code Playgroud)

结果:267479

计划:https : //www.brentozar.com/pastetheplan/?id=BJWTtILyS


第二个查询:

SELECT count(*)
FROM Audits a
    JOIN AuditRelatedIds ari ON a.Id = ari.AuditId
WHERE 
    ari.RelatedId = '1DD87CF1-286B-409A-8C60-3FFEC394FDB1'
    and a.TargetTypeId IN 
    (1,2,3,4,5,6,7,8,9,
    11,12,13,14,15,16,17,18,19,
    21,22,23,24,25,26,27,28,29,
    31,32,33,34,35,36,37,38,39,
    41,42,43,44,45,46,47,48,49,
    51,52,53,54,55,56,57,58,59,
    61,62,63,64,65,66,67,68,69,
    71,72,73,74,75,76,77,78,79)
Run Code Online (Sandbox Code Playgroud)

结果:25650

计划:https : //www.brentozar.com/pastetheplan/?id=S1v79U8kS


第一个查询大约需要一秒钟才能完成,而第二个查询大约需要 20 秒。这对我来说完全违反直觉,因为第一个查询的计数比第二个查询高得多。这是在 SQL Server 2012 上

为什么差别这么大?如何将第二个查询加速到与第一个查询一样快?


这是两个表的创建表脚本:

CREATE TABLE [dbo].[AuditRelatedIds](
    [AuditId] …
Run Code Online (Sandbox Code Playgroud)

performance sql-server optimization execution-plan query-performance

9
推荐指数
1
解决办法
236
查看次数