PostgreSQL数据库实现,如果有记录,就会更新。如果没有记录,则会添加。主键,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');使用onconflict语句更新cust_id为3的记录,修改用户名Fore: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必须使用唯一约束创建。定时更新,每天陪你进步一点点!
