Postgresql通过查询进行更新的操作

我就废话不多说了,大家还是直接看实例吧~

UPDATE tb1
SET c1=b.c1 ,
c2=b.c2
FROM b
WHERE tb1.c3 = b.c3 AND tb1.c4 = b.c4

补充:postgresql数据库 如果存在则更新(update),如果不存在则插入(insert)

格式:

insert into …… on conflict(column_name) do ……

例子:

uxdb=# create table tbl_c (id int unique, name varchar(2));
CREATE TABLE
uxdb=# insert into tbl_c values (1, ‘a’);
INSERT 0 1
uxdb=# table tbl_c;
id | name
—-+——
1 | a
(1 row)
uxdb=# insert into tbl_c values (1, ‘a’);
ERROR: duplicate key value violates unique constraint “tbl_c_id_key”
DETAIL: Key (id)=(1) already exists.
uxdb=# insert into tbl_c values (1, ‘a’) on conflict(id) do update set name=’b’;
INSERT 0 1
uxdb=# table tbl_c;
id | name
—-+——
1 | b
(1 row)

uxdb=#

注意:conflict(column_name)中的column_name必须是主键或具有唯一性才可以

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。如有错误或未考虑完全的地方,望不吝赐教。


数据运维技术 » Postgresql通过查询进行更新的操作