insert .. on conflict 特性,所以对于 upsert 场景需要采用额外的方式来进行处理,这里提供一种利用 postgresql rule 特性来进行 upsert 的方法。INSTEAD规则可以用另外一个命令取代特定的命令,或者完全不执行该命令。规则还可以用于实现表视图。规则实际上只是一个命令转换机制,或者说命令宏。这种转换发生在命令开始执行之前。CREATE TABLE my_test(id integer,num1 integer,num2 decimal,str1 varchar(20),str2 text,PRIMARY KEY(id)) distributed by (id);
create rule r1 as on insert to my_test where exists (select 1 from e t1 where t1.id=NEW.id limit 1) do instead update my_test set num1=NEW.num1,num2=NEW.num2,str1=NEW.str1,str2=NEW.str2 where id=NEW.id;
\\d my_testTable "public.my_test"Column | Type | Collation | Nullable | Default--------+-----------------------+-----------+----------+-------------------------------------id | integer | | not null | nextval('my_test_id_seq'::regclass)num1 | integer | | |num2 | numeric | | |str1 | character varying(20) | | |str2 | text | | |Indexes:"my_test_pkey" PRIMARY KEY, btree (id)Rules:r1 ASON INSERT TO my_testWHERE (EXISTS ( SELECT 1FROM my_test my_test_1WHERE my_test_1.id = new.idLIMIT 1)) DO INSTEAD UPDATE my_test SET num1 = new.num1, num2 = new.num2, str1 = new.str1, str2 = new.str2
insert into my_test (id,num1,num2,str1,str2)values(1,2,1.0,'111','555'),(1,3,2.0,'111','666');
update my_test set num1=NEW.num1,num2=NEW.num2,str1=NEW.str1,str2=NEW.str2
文档反馈