【问题标题】:SQL optimization (group by and max)SQL 优化(分组依据和最大值)
【发布时间】:2017-05-24 16:13:17
【问题描述】:

是否有机会加速下面的 sql 查询?

select 
    max(xtrid) as xtrid
  , jid
from jpltab jl
  inner join rb_cust u 
    on jl.custid = u.custid
where jl.tpe = 'Y'
  and jl.jid in (51, 52, 53, 54, 55)
  and u.org = 'INVCE'
group by jid
order by xtrid desc;

谢谢

【问题讨论】:

  • 添加索引....
  • 能否请您附上执行计划?
  • 由于Where 子句中的jl.jid 具有连续数字,请将其更改为Between 51 and 55 而不是IN (51, 52, 53, 54, 55)。这应该会给你更好的性能。看这里...stackoverflow.com/questions/3308280/…
  • 什么数据库客户端?
  • 我还会将“and u.org = 'INVCE'”移到您的 JOIN 语句中。您只希望 rb_cust 与 jpltab 匹配 custid,但仅适用于 rb_cust.org='INVCE'。从逻辑上讲,这将使初始 JOIN 变得更小,而不是为每个 custid 加入,然后为组织过滤掉。 SQL 优化器可能已经为 INNER JOIN 处理了这个问题,但我不认为它可以。

标签: sql query-optimization


【解决方案1】:

这是您的查询:

select jl.jid, max(xtrid) as xtrid
from jpltab jl inner join
     rb_cust u 
     on jl.custid = u.custid
where jl.tpe = 'Y' and
      jl.jid in (51, 52, 53, 54, 55) and
      u.org = 'INVCE'
group by jl.jid
order by xtrid desc;

我将从索引开始。我想到的是jpltab(tpe, jid, custid)rb_cust(custid, org)

【讨论】:

    【解决方案2】:

    你可以去掉'order by xtrid desc',因为你已经选择了最大值

    【讨论】:

    • 是的...您无需按组对值进行排序即可为每个组选择最大值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-24
    • 1970-01-01
    • 2014-08-06
    • 1970-01-01
    • 1970-01-01
    • 2021-11-05
    相关资源
    最近更新 更多