溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

PostgreSQL數(shù)據(jù)庫如果不存在則插入,存在則更新

發(fā)布時(shí)間:2020-10-21 09:20:38 來源:網(wǎng)絡(luò) 閱讀:21956 作者:青苗飛揚(yáng) 欄目:數(shù)據(jù)庫


新遇到一個(gè)業(yè)務(wù)需求,往postgresql中插入數(shù)據(jù)的時(shí)候需滿足:如果數(shù)據(jù)庫存在這條記錄,則進(jìn)行修改;不存在則進(jìn)行插入。

Oracle中可以用merge來解決。Pg中之前沒做過類似操作,百度查了一下,PostgreSQL 9.5 版本帶來了一個(gè)新特性:UPSERT。UPSERTINSERT, ON CONFLICT UPDATE的簡(jiǎn)寫,簡(jiǎn)而言之就是:插入數(shù)據(jù),正常時(shí)寫入,主鍵沖突時(shí)更新。

示例來看一下:

一張測(cè)試表,結(jié)構(gòu)如下:

yqm=# \d student;

           Table "public.student"

 Column |         Type          | Modifiers

--------+-----------------------+-----------

 id     | integer               |

 name   | character varying(20) |

Indexes:

    "id_cons" UNIQUE CONSTRAINT, btree (id)

目前數(shù)據(jù)如下:

yqm=# select * from student;

 id | name

----+------

  1 | a

  2 | b

  3 | c

(3 rows)

要插入的表要有一條唯一性約束,不然會(huì)報(bào)如下錯(cuò):

yqm=# insert into student values(4,'d') on conflict(id) do update set name='as';

ERROR:  there is no unique or exclusion constraint matching the ON CONFLICT specification

如果存在這種報(bào)錯(cuò),需要?jiǎng)?chuàng)建一條唯一性約束

yqm=# alter table student add constraint id_cons unique(id);

ALTER TABLE

再次插入

yqm=# insert into student values(4,'d') on conflict(id) do update set name='as';

INSERT 0 1

查看結(jié)果,已經(jīng)新增了

yqm=# select * from student;

 id | name

----+------

  1 | a

  2 | b

  3 | c

  4 | d

(4 rows)

再次執(zhí)行,會(huì)做更改操作

yqm=# insert into student values(4,'d') on conflict(id) do update set name='as';

INSERT 0 1

yqm=# select * from student;

 id | name

----+------

  1 | a

  2 | b

  3 | c

  4 | as

(4 rows)

 

 

 


向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI