【问题标题】:Most efficient way to pull Last_Updated value from a table in Postgres?从 Postgres 中的表中提取 Last_Updated 值的最有效方法?
【发布时间】:2020-06-23 00:13:31
【问题描述】:

第一篇文章在这里。我需要从表中提取最新值,但对于给定日期,此特定表中有许多条目。我对下面的两个选项做了类似的事情。

选项 1.. 将主表加入子查询表:

select t1.key, t1.date, t2.value
  from table1 t1
  join
    (select key,
          date,
          max(updated_at) as last_update      
          from table2
          group by 1,2) t2
    on t1.key = t2.key
    and t1.date = t2.date
    and t1.updated_at = t2.last_update 
order by 1,2;

选项 2.. 连接中的子查询和带有限制的降序“排序依据”:

select t1.key, t1.date, t2.value
from table1 t1 
join table2 t2
  on t1.key = t2.key 
  and t1.date = t2.date
  and t2.updated_at = (
      select updated_at
      from table2
      where key = t2.key 
      and date = t2.date
      order by updated_at desc
      limit 1)
order by 1,2;

选项 2 有点不典型,并且需要在子查询中对整个表进行排序,所以我怀疑这是最佳做法,但它可以工作并且允许子查询存在于 Join 中,所以我之前使用过它。

选项 1、选项 2 或某些选项 3 是解决此问题的最有效方法吗?什么是最佳做法?浏览 Stack 一段时间后很高兴加入,谢谢大家。

【问题讨论】:

    标签: sql database postgresql performance join


    【解决方案1】:

    我建议distinct on。我认为这个版本:

    select t1.key, t1.date, t2.value
    from table1 t1 join
         (select distinct on (key, date) key, date, updated_at as last_update
          from table2
          order by key, date, updated_at desc
         ) t2
         on t1.key = t2.key and
            t1.date = t2.date and
            t1.updated_at = t2.last_update 
    order by 1, 2;
    

    但是,我怀疑这两张桌子是一张桌子。如果是这样,您只需要:

    select distinct on (key, date) t1.*
    from table1 t1
    order by key, date, updated_at desc
    

    【讨论】:

      【解决方案2】:

      这是最好的:

      SELECT t1.key, t1.date, t2.value
      FROM table1 t1 
         JOIN table2 t2
            ON (t1.key, t1.date) = (t2.key, t2.date) 
      ORDER BY t2.updated_at
      LIMIT 1;
      

      为了提高效率,您需要在table2 (updated_at)table1 (key, date)(或table1 (key),如果选择性足够的话)上建立索引。然后 PostgreSQL 可以使用快速嵌套循环连接。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-10-20
        • 2021-08-01
        • 2018-12-24
        • 2016-11-30
        • 2021-09-25
        • 2013-06-04
        • 1970-01-01
        • 2015-08-11
        相关资源
        最近更新 更多