慢左外连接

时间:2018-01-23 12:11:56

标签: sql-server

我想知道是否有人可以就此问题向我提出建议。我有一个查询,当引入左外连接时运行缓慢。如果没有左外连接(内部代替),它会立即运行,但是在左外部它会运行20秒或更长时间。已连接的列已编制索引。如果有帮助,我的执行计划会显示哈希匹配。再次感谢您的帮助..

德里克

SELECT DISTINCT 
                dbo.Staff.strStaffName AS [Staff Name], dbo.Staff.strEmailAddress1 AS NegEmailAddress, ISNULL(dbo.qryContactEmailDJ.Address, 
                  dbo.Staff.strEmailAddress1) AS AppEmailAddress
FROM         dbo.Contacts INNER JOIN
                  dbo.Staff ON dbo.Contacts.strResponsibilityOf = dbo.Staff.strStaffName LEFT OUTER JOIN
                  dbo.qryContactEmailDJ ON dbo.Contacts.ContactPK = dbo.qryContactEmailDJ.ContactFK INNER JOIN
                  dbo.Property ON dbo.Contacts.CompanyFK = dbo.Property.CompanyFK INNER JOIN
                  dbo.qryLS_ApplicantLastMadeActive ON dbo.Contacts.ContactPK = dbo.qryLS_ApplicantLastMadeActive.ContactPK
WHERE     (dbo.Contacts.strApplicantStatus = 'Active') 
           AND (CONVERT(VarChar, dbo.qryLS_ApplicantLastMadeActive.LatestActiveDate, 112) = CONVERT(VarChar, GETDATE() - 84,112))

1 个答案:

答案 0 :(得分:0)

这会使它更具可读性和更快,问题是你在WHERE子句中比较日期的方法:

SELECT --(do you really need distinct ?)
  Staff.strStaffName AS [Staff Name],
  Staff.strEmailAddress1 AS NegEmailAddress, 
  ISNULL(con.qryContactEmailDJ.Address, Staff.strEmailAddress1) AS AppEmailAddress
FROM dbo.Contacts
JOIN dbo.Staff
ON Contacts.strResponsibilityOf = Staff.strStaffName
LEFT JOIN dbo.qryContactEmailDJ con
ON Contacts.ContactPK = con.ContactFK
JOIN dbo.Property
ON Contacts.CompanyFK = Property.CompanyFK
JOIN dbo.qryLS_ApplicantLastMadeActive qryl
ON Contacts.ContactPK = qryl.ContactPK
WHERE
  (Contacts.strApplicantStatus = 'Active') 
  AND qryl.LatestActiveDate >= dateadd(d, datediff(d, 0, GETDATE()), -84)
  AND qryl.LatestActiveDate < dateadd(d, datediff(d, 0, GETDATE()), -83)