自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Postgre SQL數(shù)據(jù)庫實(shí)現(xiàn)有記錄則更新無記錄就新增

數(shù)據(jù)庫 其他數(shù)據(jù)庫
本篇給大家介紹Postgre SQL數(shù)據(jù)庫實(shí)現(xiàn)有記錄則更新無記錄就新增的相關(guān)知識,希望對你有所幫助!

[[396425]]

 在PostgreSQL中使用on conflict關(guān)鍵字,可以很方便地實(shí)現(xiàn)有則更新無則新增的功能:

創(chuàng)建一張測試表,id為自增主鍵,cust_id為用戶id,name為用戶名稱:

  1. create table test_cust (id serial primary key, cust_id intname varchar(20)); 

為字段cust_id創(chuàng)建唯一約束:

  1. create unique index idx_tb_cust_id_unq on test_cust( cust_id); 

向表中新增三條記錄:

  1. insert into test_cust ( cust_id,namevalues (1, 'a'); 
  2. insert into test_cust ( cust_id,namevalues (2, 'b'); 
  3. insert into test_cust ( cust_id,namevalues (3, 'c'); 
  4. select * from test_cust; 

 

再次向表中增加cust_id為3的記錄時,由于cust_id有唯一約束,新增記錄會報錯:

  1. insert into test_cust ( cust_id,namevalues (3, 'b'); 

 

使用on conflict語句實(shí)現(xiàn)更新cust_id為3的記錄,將該用戶的name修改為e:

  1. insert into test_cust ( cust_id,namevalues (3, 'e'on conflict(cust_id) do update set name='e'
  2. select * from test_table; 

 

如果有記錄的時候不做任何操作,沒有記錄則新增,可以這樣來實(shí)現(xiàn):

  1. insert into test_cust ( cust_id,namevalues (3, 'e'on conflict(cust_id) do nothing; 

需要注意的是:conflict(cust_id) 中的字段cust_id必須創(chuàng)建有唯一約束。

定期更新,和你一起每天進(jìn)步一點(diǎn)點(diǎn)!

 

責(zé)任編輯:姜華 來源: 今日頭條
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號