PostgreSQL更新表時時間戳不會自動更新的解決方法,具體如下
操作系統(tǒng):CentOS7.3.1611_x64
PostgreSQL版本:9.6
問題描述
PostgreSQL執(zhí)行Insert語句時,自動填入時間的功能可以在創(chuàng)建表時實現(xiàn),但更新表時時間戳不會自動自動更新。
在mysql中可以在創(chuàng)建表時定義自動更新字段,比如 :
create table ab ( id int, changetimestamp timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP );
那PostgreSQL中怎么操作呢?
解決方案
通過觸發(fā)器實現(xiàn),具體如下:
create or replace function upd_timestamp() returns trigger as $$ begin new.modified = current_timest 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();
測試代碼:
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;
好,就這些了,希望對你有幫助。
本文github地址。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
標(biāo)簽:池州 白山 呼倫貝爾 安順 舟山 黃石 菏澤 楚雄
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《PostgreSQL更新表時時間戳不會自動更新的解決方法》,本文關(guān)鍵詞 PostgreSQL,更新,表時,時間,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。