PostgreSQL之時間戳自動更新
問題描述
PostgreSQL執行Insert語句時,自動填入時間的功能可以在創建表時實現,但更新表時時間戳不會自動自動更新。
在mysql中可以在創建表時定義自動更新字段,比如 :
create table ab (
id int,
age int,
changetimestamp timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP
);
那PostgreSQL中怎麼操作呢?
解決方案
1,通過內置的插件包moddatetime實現
create extension moddatetime;
drop table if exists t1;
create table t1 (
id serial not null primary key,
age int,
create_time timestamp(0) without time zone default now()::timestamp(0) without time zone,
update_time timestamp(0) without time zone
);
-- 自動將update_time字段更新爲最新時間
CREATE TRIGGER update_timestamp
BEFORE UPDATE ON t1
FOR EACH ROW
EXECUTE PROCEDURE moddatetime (update_time);
--測試