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
相关产品推荐
相关产品推荐

