这篇文章主要介绍“Postgre SQL数据库实现有记录则更新无记录就新增的方法”,在日常操作中,相信很多人在Postgre SQL数据库实现有记录则更新无记录就新增的方法问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Postgre SQL数据库实现有记录则更新无记录就新增的方法”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

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

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

createtabletest_cust(idserialprimarykey,cust_idint,namevarchar(20));

为字段cust_id创建唯一约束:

createuniqueindexidx_tb_cust_id_unqontest_cust(cust_id);

向表中新增三条记录:

insertintotest_cust(cust_id,name)values(1,'a');insertintotest_cust(cust_id,name)values(2,'b');insertintotest_cust(cust_id,name)values(3,'c');select*fromtest_cust;

再次向表中增加cust_id为3的记录时,由于cust_id有唯一约束,新增记录会报错:

insertintotest_cust(cust_id,name)values(3,'b');

使用on conflict语句实现更新cust_id为3的记录,将该用户的name修改为e:

insertintotest_cust(cust_id,name)values(3,'e')onconflict(cust_id)doupdatesetname='e';select*fromtest_table;

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

insertintotest_cust(cust_id,name)values(3,'e')onconflict(cust_id)donothing;

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

到此,关于“Postgre SQL数据库实现有记录则更新无记录就新增的方法”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!