PostgreSQL 9.5-

使用函数或with实现

create table test(id int primary key, info text, crt_time timestamp);
with upsert as (update test set info='test',crt_time=now() where id=1 returning *) insert into test select 1,'test',now() where not exists (select 1 from upsert where id=1);  

PostgreSQL 9.5+

PostgreSQL 9.5 引入了一项新功能,UPSERT(insert on conflict do),当插入遇到约束错误时,直接返回,或者改为执行UPDATE。

INSERT INTO table_name VALUES() ON conflict (唯一索引字段) DO
UPDATE ...
Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐