不理解为什么添加IN会导致SqlServer 2014遭受巨大的性能损失

时间:2016-08-03 17:11:34

标签: sql-server

我无法理解如何添加只添加顶部选择会导致查询从48毫秒变为7000毫秒。基本上,如果我只执行以黄色突出显示的查询,则需要48毫秒。当我添加顶部时需要7000毫秒。返回的总行数仅为60,因此我无法理解减速的原因。感觉好像它正在执行我的与会者文件中的所有行,而不仅仅是在in子句中找到的60行。

查询:

Full Query Including In Clause

Plan for full query above

Plan for just part in yellow

完整查询包含在子句中 计划上面的完整查询 计划只是黄色的一部分 原始查询:

SELECT Attendees.Id,
       Attendees.UserFirstName,
       Attendees.UserLastName,
       Attendees.Email
FROM Attendees
WHERE Id IN (
              SELECT DISTINCT dbo.Attendees.Id
              FROM dbo.SessionAttendee
                   INNER JOIN dbo.Attendees ON (
                     dbo.SessionAttendee.Attendees_username = dbo.Attendees.PKID
                     )
                   INNER JOIN dbo.Sessions ON (dbo.SessionAttendee.Sessions_id =
                     dbo.Sessions.Id)
              WHERE dbo.Sessions.CodeCampYearId = 104 AND
                    dbo.SessionAttendee.Interestlevel = 3
      )

2 个答案:

答案 0 :(得分:1)

不确定为什么需要热门查询,难道不能只从第一个查询中选择所有内容吗?

 SELECT DISTINCT
   Attendees.Id,
   Attendees.UserFirstName,
   Attendees.UserLastName,
   Attendees.Email
 FROM dbo.SessionAttendee
 INNER JOIN dbo.Attendees ON (
                 dbo.SessionAttendee.Attendees_username = dbo.Attendees.PKID
                 )
 INNER JOIN dbo.Sessions ON (dbo.SessionAttendee.Sessions_id =
                 dbo.Sessions.Id)
 WHERE dbo.Sessions.CodeCampYearId = 104 AND
                dbo.SessionAttendee.Interestlevel = 3

答案 1 :(得分:0)

您可以尝试使用EXISTS。

SELECT  a.Id,
        a.UserFirstName,
        a.UserLastName,
        a.Email
FROM    Attendees a
WHERE EXISTS (
    SELECT  1 
    FROM    dbo.Sessions s
            JOIN SessionAttendee sa ON sa.Sessions_id = s.Id 
    WHERE   s.CodeCampYearId = 104
            AND sa.Interestlevel = 3
            AND sa.Attendees_username = a.PKID
)

IN部分可能不会像DISTINCT部分那样影响性能