zl程序教程

您现在的位置是:首页 >  数据库

当前栏目

Postgre SQL数据库实现有记录则更新无记录就新增

2023-03-14 09:41:57 时间

 在PostgreSQL中使用on conflict关键字,可以很方便地实现有则更新无则新增的功能:

创建一张测试表,id为自增主键,cust_id为用户id,name为用户名称:

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

为字段cust_id创建唯一约束:

  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语句实现更新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; 

 

如果有记录的时候不做任何操作,没有记录则新增,可以这样来实现:

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

需要注意的是:conflict(cust_id) 中的字段cust_id必须创建有唯一约束。

定期更新,和你一起每天进步一点点!