摆脱哈希匹配加入的这个问题?

时间:2018-03-12 07:34:16

标签: sql-server tsql azure-sql-database

我有以下查询,大约需要26行才能返回8700行数据。

SELECT
  R.ClientReferralID,
  R.ClientID,
  C.FirstName,
  C.LastName,
  C.FullName,
  dbo.fnGetLocalDate(R.ReferralDate) as ReferralDate,
  RT.ReferralTypeName,
  R.ReferralTypeOther,
  RT2.ReferredToName,
  R.ReferredToOther,
  R.ReferredByID,
  U.FullName as ReferredBy,
  TS.TimeSpentName,
  R.Notes,
  L.ReferralLocationID,
  L.ReferralLocationName as Location,
  R.ReferralLetterSentID,
  R.ReferralLetterOnFileID,
  dbo.fnGetLocalDate(R.DateCreated) as DateCreated,
  U2.FullName as UserCreated,
  dbo.fnGetLocalDate(R.DateModified) as DateModified,
  U3.FullName as UserModified
 FROM
  ClientReferral R
 INNER JOIN Client C on
  R.ClientID = C.ClientID
 INNER JOIN LookUp.ReferralType RT on 
  R.ReferralTypeID = RT.ReferralTypeID
 INNER JOIN LookUp.ReferredTo RT2 on
  R.ReferredToID = RT2.ReferredToID
 INNER JOIN UserAccount U on
  R.ReferredByID = U.UserAccountID
 INNER JOIN LookUp.TimeSpent TS on
  R.TimeSpentID = TS.TimeSpentID
 INNER JOIN LookUp.ReferralLocation L on 
  R.ReferralLocationID = L.ReferralLocationID
 INNER JOIN UserAccount U2 on 
  R.UserCreated = U2.UserAccountID
 LEFT JOIN UserAccount U3 on 
  R.UserModified = U3.UserAccountID
 WHERE
  (R.ReferralDate >= @StartDate or @StartDate is null) and
  (R.ReferralDate <= @EndDate or @EndDate is null)
 ORDER BY 
  R.DateCreated DESC

可以在此处查看执行计划:

https://www.brentozar.com/pastetheplan/?id=B1A5ji7tf

我认为哈希匹配加入中最昂贵的操作是65%。我期待以下索引改进,但不是:

CREATE NONCLUSTERED INDEX [Name] ON [dbo].[ClientReferral]
(
    [ClientID] ASC
)

任何人都能看到我能在这做什么?如果需要一些样本数据,请告诉我。

2 个答案:

答案 0 :(得分:0)

尝试添加索引

ClientReferral ReferralDate  

ClientReferral ReferralDate, ClientID   
ClientReferral ClientID, ReferralDate 

答案 1 :(得分:0)

首先改变

WHERE(R.ReferralDate&gt; = @StartDate或@StartDate为空)和(R.ReferralDate&lt; = @EndDate或@EndDate为空)

WHERE R.ReferralDate BETWEEN ISNULL(@StartDate,CAST(0 AS datetime2)) AND ISNULL(@EndDate,CAST(999999 AS datetime2))

之后在

上创建一个索引
ClientReferral(ReferralDate, ClientID, ReferralTypeID, ReferredToID, ReferredByID, TmeSpentID, ReferralLocationID, UserCreated, UserModified, DateCreated, DateModified) INCLUDE(ClientReferralID, ReferralTypeOther, ReferredToOther, Notes, ReferralLetterSentID, ReferralLetterOnFileID)

还显示

的代码
fnGetLocalDate