Postgre SQL數(shù)據(jù)庫實(shí)現(xiàn)有記錄則更新無記錄就新增
作者:數(shù)據(jù)超酷
本篇給大家介紹Postgre SQL數(shù)據(jù)庫實(shí)現(xiàn)有記錄則更新無記錄就新增的相關(guān)知識,希望對你有所幫助!
在PostgreSQL中使用on conflict關(guān)鍵字,可以很方便地實(shí)現(xiàn)有則更新無則新增的功能:
創(chuàng)建一張測試表,id為自增主鍵,cust_id為用戶id,name為用戶名稱:
- create table test_cust (id serial primary key, cust_id int, name varchar(20));
為字段cust_id創(chuàng)建唯一約束:
- create unique index idx_tb_cust_id_unq on test_cust( cust_id);
向表中新增三條記錄:
- insert into test_cust ( cust_id,name) values (1, 'a');
- insert into test_cust ( cust_id,name) values (2, 'b');
- insert into test_cust ( cust_id,name) values (3, 'c');
- select * from test_cust;
再次向表中增加cust_id為3的記錄時,由于cust_id有唯一約束,新增記錄會報錯:
- insert into test_cust ( cust_id,name) values (3, 'b');
使用on conflict語句實(shí)現(xiàn)更新cust_id為3的記錄,將該用戶的name修改為e:
- insert into test_cust ( cust_id,name) values (3, 'e') on conflict(cust_id) do update set name='e';
- select * from test_table;
如果有記錄的時候不做任何操作,沒有記錄則新增,可以這樣來實(shí)現(xiàn):
- insert into test_cust ( cust_id,name) values (3, 'e') on conflict(cust_id) do nothing;
需要注意的是:conflict(cust_id) 中的字段cust_id必須創(chuàng)建有唯一約束。
定期更新,和你一起每天進(jìn)步一點(diǎn)點(diǎn)!
責(zé)任編輯:姜華
來源:
今日頭條