【问题标题】:Querying max of timestamp from PostgreSQL DB从 PostgreSQL 数据库查询最大时间戳
【发布时间】:2015-04-01 10:55:06
【问题描述】:

假设在名为tracker 的 PostgreSQL 表中有 3 行。我想单独获取最新的更新记录。请帮我实现它。

(issue_id,priority,ingest_date)
(1,1,"2015-01-27 00:00:00")
(1,2,"2015-01-28 00:00:00")
(1,3,"2015-01-29 00:00:00")

我试着给

select * 
from tracker 
where ingest_date = (select max(ingest_date) from tracker);

这对我来说很好。 但是有没有更好的方法可以查询数据库?

提前致谢。

我想要类似的东西

select * 
from etl_change_fact 
where ingest_date = max(ingest_date);

但我得到了这个错误

**ERROR: aggregates not allowed in WHERE clause
**

【问题讨论】:

  • 如果您在ingest_date 上有一个索引,那么您的第一个查询可能是最有效的方法。
  • 我同意马的观点。假设一个索引,子查询将通过大多数其他方法将索引或表扫描转换为索引查找。非常有效。

标签: sql performance postgresql select optimization


【解决方案1】:

您可以按以下方式进行。只需选择最新的记录...

 SELECT * from tracker ORDER BY ingest_date DESC LIMIT 1

此查询将始终只返回一条记录。 如果 ingest_date 包含重复项,您的查询可以返回多行。

【讨论】:

    【解决方案2】:

    如果您知道ingest_date 是唯一的(即只有一行是最新的),您可以使用fetch first 子句:

    SELECT      *
    FROM        tracker
    ORDER BY    ingest_date DEXC
    FETCH FIRST 1 ROWS ONLY
    

    如果这个假设不能成立,您可以使用rank 窗口函数返回所有“最新”记录:

    SELECT issue_id, priority, ingest_date
    FROM   (SELECT issue_id, priority, ingest_date, 
                   RANK() OVER (ORDER BY ingest_date DESC) AS rk
            FROM   tracker)
    WHERE  rk = 1
    

    【讨论】:

    • 真的没必要为这么简单的问题创建窗口,select * from table where col = (select max(col) from table) 会产生更高效的查询计划。
    猜你喜欢
    • 1970-01-01
    • 2018-08-16
    • 2011-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 2020-04-12
    • 1970-01-01
    相关资源
    最近更新 更多