You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PostgreSQL如何更新指定列对应最新日期的记录值

解决方案

要更新col为'a'的最新日期记录,有两种常用实现方式,适配不同数据库环境:

方式一:子查询获取最大日期

这种写法简单通用,支持大多数数据库(MySQL、PostgreSQL、SQL Server等):

update table
set date = '2022-09-30'
where col='a'
and date = (select max(date) from table where col='a');

逻辑说明:通过子查询筛选出col='a'的最大(最新)日期,仅匹配该日期的记录进行更新。如果存在多条col='a'且日期等于最新日期的记录,所有这些记录都会被更新。

方式二:窗口函数定位最新记录

适用于支持窗口函数的数据库(MySQL 8.0+、PostgreSQL、SQL Server等):

update table
set date = '2022-09-30'
where (col, date) in (
    select col, date
    from (
        select col, date,
               row_number() over (partition by col order by date desc) as rn
        from table
        where col='a'
    ) t
    where rn = 1
);

逻辑说明:

  • 用row_number()窗口函数按col分组,对date降序排序,最新日期的记录会被标记为rn=1
  • 外层查询筛选出rn=1的记录,匹配后完成更新

如果存在多条col='a'且日期相同的最新记录,想要全部更新的话,可将row_number()替换为rank()。

内容的提问来源于stack exchange,提问作者Heisenberg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 19:40:29