【问题标题】:How to get the latest records of the multiple values of same column in PostgreSQL?如何获取PostgreSQL中同一列的多个值的最新记录?
【发布时间】:2013-06-26 00:18:41
【问题描述】:

我有一个具有以下结构的数据库

 url  update_time                 dns_time
 -------------------------------
 url1  2013-04-05 08:03:23       0.897
 url2  2013-09-03 08:03:45       0.765
 url1  2013-08-23 09:23:34       2.457
 url3  2013-08-34 09:45:47       1.456
 //and so on

现在我只想检索每个 url 的最新记录。如何使用 PostgreSQL 选择查询来实现这一点。

我尝试过使用

 select url,
        update_time,
        dns_time 
 from dns_lookup_table 
 where url in('url1','url2','url3') 
 order by desc limit 1

但它给了我最后一条记录的 url3 最新值。我尝试使用 desc limit 3 来获取所有 3 个 url 的最新值。我要检索url1url2url3的最新记录。只有最新记录。并且表dns_lookup_table 具有动态进入其中的记录。有时,如果不可用,则无法插入 url 记录。所以订单缺失。所以我认为desc limit是不可能的。

【问题讨论】:

  • update_time的类型是什么?
  • 所以订单丢失”到底是什么意思?
  • 如果我使用 desc 限制 5,Urls 的顺序将会丢失。如果记录不可用,并且没有插入数据库的 url
  • update_time 是 postgresql 中的时间戳类型

标签: sql postgresql select


【解决方案1】:

您可以使用窗口函数来获取每个 URL 的最新行:

select *
from (
   select url, 
          update_time, 
          dns_time, 
          row_number() over (partition by url order by update_time desc) as rnk
   from dns_lookup_table
) as t
where rnk = 1

SQLFiddle 示例:http://sqlfiddle.com/#!12/fbd38/1


编辑

你也可以这样使用:

select *
from dns_lookup_table lt
  join (
     select url, 
            max(update_time) as latest_time
     from dns_lookup_table
     group by url
  ) as mt on mt.latest_time = lt.update_time 
         and mt.url = lt.url;

【讨论】:

  • 我使用的是postgresql 9.0版本
  • @user2515189: 那么窗口函数就可以工作了。您可能复制了错误的代码。您能否将显示问题的示例上传到sqlfiddle.com
【解决方案2】:
SELECT *
 FROM dns_lookup_table lut
 WHERE NOT EXISTS (
   SELECT *
   FROM dns_lookup_table nx
   WHERE nx.url = lut.url
     AND nx.update_time > lut.update_time
   );  

【讨论】:

    猜你喜欢
    • 2020-10-09
    • 1970-01-01
    • 2016-09-01
    • 2022-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-18
    • 2022-12-21
    相关资源
    最近更新 更多