pgsql merge方法


在网上看到很多关于psql的merge方法,很多都是用函数function来实现的,其实在pgsql10以后可以通过sql来直接实现merge方法

具体语法如下:

  with "别名" as (update 表名 set 字段名1= '更新的值',字段名2='更新的值' where 主键=需要更新的主键的值 returning *)

insert into 表名(字段名1,字段名2) select '更新的值','更新的值' where (select count(*) from 别名) = 0

我自己写了个例子:

create table test(
id serial primary key,
aa varchar(10),
bb varchar(10)
);
insert into test(aa,bb) values('qw','rt');
insert into test(aa,bb) values('vb','ad');
insert into test(aa,bb) values('er','fg');

with "te" as (update test set aa = 'test',bb='test' where id =4 returning *)
insert into test(aa,bb) select 'test','test' where (select count(*) from te) = 0

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM