SQL子查询和连接性能问题

时间:2012-11-09 13:40:02

标签: sql sql-server-2008 tsql sql-server-2005 sql-server-2000

       `select * from DETAIL a
        where a.BUILD > GETDATE() - 90 s
        and (a.IN + a.Rt) NOT IN (SELECT Sample_IN + Rt FROM  SUMMARY)                  
        and (a.Rt + a.Err) IN 
       (SELECT Rt + Err 
        FROM SUMMARY 
        where (sample_in + rt + err) NOT IN 
       (SELECT in + rt + err FROM DETAIL)) 
        group by a.rt, a.plant, a.in, a.build`

此查询显示性能问题,它在sql2000服务器中运行速度更快,但在sql2008R2中表现不佳。两个环境中的表具有相同的属性(列数据类型和索引)。我猜在select子句的“+”运算符中有一些可能性。有谁可以帮助我?

2 个答案:

答案 0 :(得分:3)

连接字段时索引不起作用。您可以在表中创建已经组合这些字段的列,并在这些字段上创建索引。这将改善你的表现。

另外,请注意此查询将运行得更快并使用您当前的索引(请原谅我输入拼写错误,您没有包含表定义):

select * 
  from DETAIL a
 where a.BUILD > DateAdd( Day, -90, GetDate() )
   and not exists ( select null 
                      from SUMMARY 
                     where SUMMARY.Sample_IN = a.IN and SUMMARY.Rt  = a.Rt )
   and exists ( select null
                 from SUMMARY 
                where not exists ( select null
                                     from DETAIL 
                                    where DETAIL.in = SUMMARY.Sample_IN 
                                      and DETAIL.Rt = SUMMARY.Rt 
                                      and DETAIL.Err = SUMMARY.Err)
                  and a.Rt = SUMMARY.Rt
                  and a.Err = SUMMARY.Err ) 
group by a.rt, a.plant, a.in, a.build

答案 1 :(得分:0)

    select * from DETAIL a 
    left outer join SUMMARY sm1
      on a.IN = sm1.Sample_IN 
     and a.Rt = sm1.Rt 
    join SUMMARY sm2
      on a.Rt = sm2.Rt
     and a.Err = sm2.Err
    left outer join Detail d 
      on sm2.Sample_IN = d.in
     and sm2.rt = d.rt
     and sm2.err = d.err
    where a.BUILD > GETDATE() - 90 s
    and sm1.Rt is null 
    and d.in is null
    group by a.rt, a.plant, a.in, a.build

这是使用连接。对于你的Dominic Goulet存在的问题可能会更好。 1