PostgreSQL之时间戳自动更新

问题描述

会宁ssl适用于网站、小程序/APP、API接口等需要进行数据传输应用场景,ssl证书未来市场广阔!成为成都创新互联公司的ssl证书销售渠道,可以享受市场价格4-6折优惠!如果有意向欢迎电话联系或者加微信:13518219792(备注:SSL证书合作)期待与您的合作!

PostgreSQL执行Insert语句时,自动填入时间的功能可以在创建表时实现,但更新表时时间戳不会自动自动更新。

在mysql中可以在创建表时定义自动更新字段,比如 :

 
 
 
  1. create table ab ( 
  2.   id int, 
  3.   changetimestamp timestamp 
  4.     NOT NULL 
  5.     default CURRENT_TIMESTAMP 
  6.     on update CURRENT_TIMESTAMP 
  7. );  

那PostgreSQL中怎么操作呢?

解决方案

通过触发器实现,具体如下:

 
 
 
  1. create or replace function upd_timestamp() returns trigger as 
  2. $$ 
  3. begin 
  4.     new.modified = current_timestamp; 
  5.     return new; 
  6. end 
  7. $$ 
  8. language plpgsql; 
  9.  
  10. drop table if exists ts; 
  11. create table ts ( 
  12.     id      bigserial  primary key, 
  13.     tradeid integer , 
  14.     email varchar(50), 
  15.     num integer, 
  16.     modified timestamp default current_timestamp 
  17. ); 
  18. create trigger t_name before update on ts for each row execute procedure upd_timestamp();  

测试代码:

 
 
 
  1. insert into ts (tradeid,email,num) values (1223,'mike_zhang@live.com',1); 
  2. update ts set email='Mike_Zhang@live' where tradeid = 1223 ; 
  3.  
  4. create unique index ts_tradeid_idx on ts(tradeid); 
  5. insert into ts(tradeid,email,num) values (1223,'Mike_Zhang@live.com',2) on conflict(tradeid) do update 
  6. set email = excluded.email,num=excluded.num; 
  7.  
  8. select * from ts; 
  9. -- delete from ts;  

好,就这些了,希望对你有帮助。

网站题目:PostgreSQL之时间戳自动更新
本文URL:http://www.hantingmc.com/qtweb/news47/256147.html

网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联