原文:https://blog.csdn.net/rudygao/article/details/50498908
–pg 9.5 版本支持 “UPSERT” 特性, 这个特性支持 INSERT 语句定义 ON CONFLICT DO UPDATE/IGNORE 属性,当插入 SQL 违反约束的情况下定义动作,而不抛出错误
–创建测试数据表
create table t (id int constraint idx_t_id primary key,name varchar(20) constraint cst_name not null);
insert into t values(1,'rudy');
postgres=# select * from t;
id | name
----+------
1 | rudy
(1 row)
–根据字段,当id冲突时更新name值
postgres=# insert into t values(1,'rudy1') ON CONFLICT(id) do update set name=EXCLUDED.name ;
INSERT 0 1
postgres=# select * from t;
id | name
----+-------
1 | rudy1
–也可以直接指定约束名,此时不需要字段,在实际应用中,最好使用字段名
postgres=# insert into t values(2,'rudy3') ON CONFLICT ON CONSTRAINT idx_t_id do update set name=EXCLUDED.name ;
INSERT 0 1
postgres=# select * from t;
id | name
----+-------
1 | rudy1
2 | rudy3
(2 rows)
–根据where条件选择性更新,由于id没有大于10的数据,故更新0条数据
postgres=# insert into t values(2,'rudy4') ON CONFLICT ON CONSTRAINT idx_t_id do update set name=EXCLUDED.name where t.id>10 ;
INSERT 0 0
postgres=# select * from t;
id | name
----+-------
1 | rudy1
2 | rudy3
–只插入满足条件的数据行
postgres=# insert into t values(2,'rudy4'),(3,'rudy3') ON CONFLICT(id) do nothing ;
INSERT 0 1
postgres=# select * from t;
id | name
----+-------
1 | rudy1
2 | rudy3
3 | rudy3