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