[[396425]]
在PostgreSQL中使用on conflict关键字,现有新无新增可以很方便地实现有则更新无则新增的记录记录功能:
创建一张测试表,id为自增主键,则更cust_id为用户id,数据name为用户名称:
- create table test_cust (id serial primary key,库实 cust_id int, name varchar(20));
为字段cust_id创建唯一约束:
- 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语句实现更新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;
如果有记录的时候不做任何操作,没有记录则新增,数据可以这样来实现:
- insert into test_cust ( cust_id,库实name) values (3, 'e') on conflict(cust_id) do nothing;
需要注意的是:conflict(cust_id) 中的字段cust_id必须创建有唯一约束。
定期更新,现有新无新增和你一起每天进步一点点!
记录记录记录记录责任编辑:姜华 来源: 今日头条 数据库Postgre SQL无则新增
(责任编辑:时尚)
文投控股(600715.SH):北京文创定增基金已减持17.89万股 占公司总股份的0.0096%
*ST海航(600221.SH):2月客运量同比升419.17% 货邮载运率32.77%
三峡集团当好能源供应“稳定器” 国内累计新增装机近260万千瓦