PostgreSQL solution where the timestamp is not automatically updated when the table is updated
- 2020-05-06 11:56:45
- OfStack
The solution is that the timestamp is not automatically updated when PostgreSQL updates a table, as shown in
Operating system: CentOS 7.3.1611_x64
PostgreSQL version: 9.6
problem description
The ability to automatically time when PostgreSQL executes Insert statements can be implemented when a table is created, but the timestamp is not automatically updated when the table is updated.
In mysql, you can define auto-update fields when you create a table, such as
create table ab (
id int,
changetimestamp timestamp
NOT NULL
default CURRENT_TIMESTAMP
on update CURRENT_TIMESTAMP
);
So how does PostgreSQL work?
solution
Through the trigger implementation, as follows:
create or replace function upd_timestamp() returns trigger as
$$
begin
new.modified = current_timestamp;
return new;
end
$$
language plpgsql;
drop table if exists ts;
create table ts (
id bigserial primary key,
tradeid integer ,
email varchar(50),
num integer,
modified timestamp default current_timestamp
);
create trigger t_name before update on ts for each row execute procedure upd_timestamp();
Test code:
insert into ts (tradeid,email,num) values (1223,'mike_zhang@live.com',1);
update ts set email='Mike_Zhang@live' where tradeid = 1223 ;
create unique index ts_tradeid_idx on ts(tradeid);
insert into ts(tradeid,email,num) values (1223,'Mike_Zhang@live.com',2) on conflict(tradeid) do update
set email = excluded.email,num=excluded.num;
select * from ts;
-- delete from ts;
Ok, that's all, I hope it helped you.
The github address for this article.