2012-09-26 38 views
1

我需要優化下面的查詢,任何人都可以幫忙嗎?我知道這是造成這個問題的不存在部分,因爲它正在進行大規模的表掃描,但我是新手,任何人都可以提供任何建議?SQL查詢優化不存在

select count(*) 
from Job j 
where company = 'A' 
and branch = 'Branch123' 
and engineerNumber = '000123' 
and ID > 60473 
and not exists(
select JobNumber, Company, Branch 
from OutboundEvents o 
where o.JobNumber = j.JobNumber 
    and o.branch = j.branch 
    and o.company = j.company 
    and o.Formtype = 'CompleteJob') 
+0

你能分享工作和出站事件(包括索引)的架構,和後一個實際的執行計劃(.sqlplan)在哪裏很容易下載? –

回答

7
create index [<indexname>] on [Job] (
    [company], [branch], [engineerNumber], [ID]) include ([JobNumber]); 
create index [<indexname>] on [OutboundEvents] (
    [company], [branch], [JobNumber], [Formtype]); 

你是不是優化查詢,是您優化的數據模型。從閱讀Designing Indexes開始。

+1

如果在第一個索引中包含了[JobNumber],那麼會有什麼區別嗎? –

+0

@ypercube:是的,應該是,我沒有注意到 –

+3

請注意,添加這些索引來優化此特定查詢並不會將剩餘的工作量考慮在內。如果你的寫:讀比例很高,你可能會爲維護這些指數付出高昂的代價。我並不是說這個答案錯了​​,只是需要考慮整個系統,而不僅僅是一個查詢。這就是爲什麼我們不會盲目地遵循數據庫引擎優化顧問的建議(或執行計劃或缺失的索引DMV),這些建議會告訴我們基於有限的和孤立的信息創建索引。 –

0

謝謝大家對你有幫助的見解。我有很多東西要學:)我設法使用此查詢削減執行時間從1min7sec下降到只有1秒以內:

select count(*) 
from job 
where company = 'A' 
and branch = 'Branch123' 
and EngineerNumber = '000123' 
AND id> 60473 
AND JobNumber not in(
    select Jobnumber from outboundevents b 
    where b.company = 'A' 
    AND b.Branch = 'Branch123' 
    and b.Formtype = 'CompleteJob' 
    and jobnumber in (
     select jobnumber from Job 
     where company = 'A' 
     and branch = 'Branch123' 
     and engineerNumber = '000123' 
     and ID > 60473) 
) 
+0

我也在Remus建議的桌子上放了一個索引。 – Louise

+1

你應該知道,如果'Jobnumber'爲空,'not in'可能會比'not exists'的性能差,並且有令人驚訝的結果(子查詢中存在null表示沒有行將從外部查詢返回) –