服务器之家:专注于服务器技术及软件下载分享
分类导航

Mysql|Sql Server|Oracle|Redis|MongoDB|PostgreSQL|Sqlite|DB2|mariadb|Access|数据库技术|

香港云服务器
服务器之家 - 数据库 - PostgreSQL - Postgresql通过查询进行更新的操作

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

2021-03-08 17:45逐梦诛仙 PostgreSQL

这篇文章主要介绍了Postgresql通过查询进行更新的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

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

?
1
2
3
4
5
UPDATE tb1
SET c1=b.c1 ,
c2=b.c2
FROM b
WHERE tb1.c3 = b.c3 AND tb1.c4 = b.c4

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

格式:

?
1
insert into ...... on conflict(column_name) do ......

例子:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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必须是主键或具有唯一性才可以

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

原文链接:https://blog.csdn.net/zs871893/article/details/88827606

延伸 · 阅读

精彩推荐
676