在Postgres中添加current_timestamp和days列的总和

ega*_*aga 3 postgresql timestamp

我希望通过将天数添加到当前时间来更新列.在pseudosyntax中它将是:

UPDATE foo
SET time = current_timestamp + days::integer
Run Code Online (Sandbox Code Playgroud)

days是同一个表中的一列.

Mic*_*uen 6

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);
Run Code Online (Sandbox Code Playgroud)

现在这可行:

update foo set time = current_timestamp + 3 /* day variable here, 
or a column from your table */
Run Code Online (Sandbox Code Playgroud)

注意:

出于某种原因,在Postgres中内置了一个到目前为止的整数,这可以工作:

select current_timestamp::date + 3 -- but only a date
Run Code Online (Sandbox Code Playgroud)

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

select current_timestamp + 3
Run Code Online (Sandbox Code Playgroud)


Mic*_*uen 5

select now() + cast('1 day' as interval) * 3 -- example: 3 days
Run Code Online (Sandbox Code Playgroud)