使用sql左外连接查询减少执行时间

时间:2012-11-05 20:32:13

标签: sql sql-server-2008-r2

如何使用此sql查询减少执行时间?执行和返回行花了一分多钟。(在Sql server management studio 2008中执行)

if(@NotInvoiced =1)
BEGIN
Select @Command = 
'select Distinct C.FileID, C.FileName, convert(nvarchar,C.DateReported,111) AS ''DateReported'', 
C.FileDetailsPlainText, CFIT.Level3 as ''InvestigationType'', INV.FName + '' '' + INV.LName AS ''Name'', 
convert(nvarchar,DD,111) AS ''DD'', i.FirstName + '' '' + i.LastName AS ''ReportedBy''
from CaseFiles C 
join InvestigatorCaseFileAccess IA on C.FileID=IA.CaseFileID 
LEFT OUTER JOIN CaseFileTimeBills tb on C.FileID=tb.FileID
LEFT OUTER JOIN CaseFileExpenses e on C.FileID=e.FileID

left join Element07a_Persons i on i.PersonID = c.PersonID
LEFT OUTER JOIN CaseFileInvestigationTypes CFIT ON C.InvestigationTypeID = CFIT.InvestigationTypeID 
LEFT OUTER JOIN Investigators INV ON C.InvestigatorID = INV.InvestigatorID
where (tb.InvNumber IS null OR e.InvNumber IS null) and Deleted=0 and IA.InvestigatorID=' + CONVERT (nvarchar(max),@InvestigatorID) + ' and IA.AllowAccess = ''True''
 and tb.FileID = C.FileID or e.FileID=C.FileID '
END

1 个答案:

答案 0 :(得分:1)

正如我们在评论中发现的那样,您的问题似乎是tb.FileID = C.FileID or e.FileID=C.FileID周围缺少括号。

添加这些括号从根本上改变了过滤语义,因此会更改您获得的数据。这就像没有括号的原始查询返回大量数据,或者至少比较每一个可能的行时只需比较一些。

Marlin Pierce很好地观察到,对这些OR进行括号化可以让DBMS使用利用指数(例如条件Deleted=0),而不是之前。