SQL查询优化不存在

时间:2012-09-26 13:14:08

标签: sql sql-server-2005 optimization

我需要优化以下查询,有人可以帮忙吗?我知道这是导致问题的不存在部分,因为它正在进行大规模的表扫描,但我是新手,有人可以给出任何建议吗?

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')

2 个答案:

答案 0 :(得分:7)

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

您优化的查询不是您优化的数据模型。首先阅读Designing Indexes

答案 1 :(得分:0)

谢谢大家的有益见解。我有很多要学习:)我设法使用此查询将执行时间从1分7秒缩短到不到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)
)