【问题标题】:Adding sum of current_timestamp and days column in Postgres在 Postgres 中添加 current_timestamp 和 days 列的总和
【发布时间】:2009-05-08 06:32:15
【问题描述】:

我想通过将天数添加到当前时间来更新列。在伪语法中是:

UPDATE foo
SET time = current_timestamp + days::integer

days 是同一张表中的一列。

【问题讨论】:

  • 我忘了说“天”是同一张表中的一列,不是常数。

标签: postgresql timestamp


【解决方案1】:
create function add_days_to_timestamp(t timestamptz, d int) 
returns timestamptz
as
$$
begin
    return t + interval '1' day * d;
end; 
$$ language 'plpgsql';


create operator + (leftarg = timestamptz, rightarg = int, 
         procedure = add_days_to_timestamp);

现在这可以工作了:

update foo set time = current_timestamp + 3 /* day variable here, 
or a column from your table */

注意:

由于某种原因,在 Postgres 中内置了向日期添加整数,这会起作用:

select current_timestamp::date + 3 -- but only a date

这不会(除非您定义自己的运算符,见上文):

select current_timestamp + 3

【讨论】:

  • 谢谢,这真的让我大开眼界,我可以用 postgresql 做些什么
【解决方案2】:
select now() + cast('1 day' as interval) * 3 -- example: 3 days

【讨论】:

  • 这正是我所需要的。我不知道为什么这不是你回答的一部分@Michael Buen
【解决方案3】:

calculatedDate 时间戳,无时区;

calculatedDate := current_timestamp + interval '1' day * days_count; 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-11
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    • 2017-04-05
    • 2019-02-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多