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

数据库 其他数据库
本篇给大家介绍Postgre SQL数据库实现有记录则更新无记录就新增的相关知识,希望对你有所帮助!

[[396425]]

 在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必须创建有唯一约束。

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

 

责任编辑:姜华 来源: 今日头条
相关推荐

2011-03-04 17:30:42

Oracle数据库

2011-03-21 17:25:08

SQL Server数重复记录

2009-05-08 10:15:04

LINQ插入删除

2018-09-11 17:13:23

MySQ数据库重复记录

2011-08-04 13:31:50

数据库记录更改日志触发器

2010-07-12 15:49:53

MS SQL Serv

2023-08-01 09:30:12

SQL Server数据库

2020-12-10 06:23:19

数据库阿里云RDS

2010-07-07 17:05:39

SQL Server数

2010-11-15 15:06:58

ORACLE数据库记录

2010-07-02 13:50:11

SQL Server数

2010-09-10 13:50:51

SQLCOUNT函数

2009-12-23 10:02:46

ADO数据库

2010-07-22 10:45:45

SQL Server数

2009-12-28 09:50:32

ADO数据库

2010-05-28 10:48:52

MySQL数据库

2011-08-17 09:13:08

MySQL数据库多条记录的单个字段

2010-06-01 17:45:57

MySQL数据库

2015-11-09 15:45:40

2019-09-22 21:34:59

数据库平滑变更表结构
点赞
收藏

51CTO技术栈公众号