【问题标题】:SQL subquery and join performance issueSQL 子查询和连接性能问题
【发布时间】:2012-10-29 20:07:01
【问题描述】:
       `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 中表现不佳。两个环境中的表具有相同的属性(列数据类型和索引)。我猜想选择子句的“+”运算符有一些可能性。谁能帮帮我?

【问题讨论】:

  • 我对sqlserver不熟悉,所以不知道能不能做,但是为什么不用(a.in,a.Rt) not in (select sample_IN,Rt from Summary)

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


【解决方案1】:

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

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

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

【讨论】:

  • 您好@domonic 感谢您的建议。上面的查询在 sql2000 服务器上运行良好,但问题出在 sql2008 服务器上,你对此有什么想法吗?连接的列是字符类型..两个服务器中的表具有相同的属性。
【解决方案2】:
    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

【讨论】:

  • 谢谢@blam,我怀疑相同的查询在sql2000中运行良好,但为什么在sql2008中失败..我认为可能存在与设置相关的问题..你能指导我吗?
  • SQL2008中是否有相同的索引。比较查询计划,看看有什么不同。
  • 是的,两台服务器上的索引相同。问题仍然存在
  • 你对比过查询计划吗?
  • 没有人,我知道 oracle 但 sql 有点不同。我不知道如何从图形表示中推断出来..
猜你喜欢
  • 2011-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-08
  • 1970-01-01
  • 2011-06-29
  • 2019-08-06
  • 1970-01-01
相关资源
最近更新 更多