PostgreSQL更新表時時間戳記不會自動更新的解決方案,postgresql自動更新

來源:互聯網
上載者:User

PostgreSQL更新表時時間戳記不會自動更新的解決方案,postgresql自動更新

PostgreSQL更新表時時間戳記不會自動更新的解決方案,具體如下

作業系統:CentOS7.3.1611_x64

PostgreSQL版本:9.6

問題描述

PostgreSQL執行Insert語句時,自動填入時間的功能可以在建立表時實現,但更新表時時間戳記不會自動自動更新。

在mysql中可以在建立表時定義自動更新欄位,比如 :

create table ab ( id int, changetimestamp timestamp  NOT NULL  default CURRENT_TIMESTAMP  on update CURRENT_TIMESTAMP);

那PostgreSQL中怎麼操作呢?

解決方案

通過觸發器實現,具體如下:

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();

測試代碼:

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 updateset email = excluded.email,num=excluded.num;select * from ts;-- delete from ts;

好,就這些了,希望對你有協助。

本文github地址。

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.