在网上看到很多关于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