postgres 冲突定义--upset
01,场景定义
一般某些值可能设置唯一键导致插入数据出错
02,场景复现
--创建表 CREATE TABLE kingle_study_5 ( name VARCHAR(200) PRIMARY KEY, time INT4, insert_time TIMESTAMP(0) WITHOUT TIME ZONE );
数据植入
INSERT INTO kingle_study_5 VALUES ('a',1),('b',2),('a',1);
执行的时候就会发现一整个这个问题,主键冲突
03,upset 来袭
语法定义在insert 下面 Command: INSERT Description: create new rows in a table Syntax: [ WITH [ RECURSIVE ] with_query [, ...] ] INSERT INTO table_name [ AS alias ] [ ( column_name [, ...] ) ] [ OVERRIDING { SYSTEM | USER } VALUE ] { DEFAULT VALUES | VALUES ( { expression | DEFAULT } [, ...] ) [, ...] | query } [ ON CONFLICT [ conflict_target ] conflict_action ] [ RETURNING * | output_expression [ [ AS ] output_name ] [, ...] ] where conflict_target can be one of: ( { index_column_name | ( index_expression ) } [ COLLATE collation ] [ opclass ] [, ...] ) [ WHERE index_predicate ] ON CONSTRAINT constraint_name and conflict_action is one of: DO NOTHING DO UPDATE SET { column_name = { expression | DEFAULT } | ( column_name [, ...] ) = [ ROW ] ( { expression | DEFAULT } [, ...] ) | ( column_name [, ...] ) = ( sub-SELECT ) } [, ...] [ WHERE condition ]
001,冲突更新操作
INSERT INTO kingle_study_5 (name,time) VALUES ('b',2),('a',1) ON conflict(name) -- 定义冲突的键 DO UPDATE SET -- 冲突设置 time = kingle_study_5.time + EXCLUDED.time,insert_time= now();
我们查询看看是不是成功了
再执行一次 同样的操作
发现每次 插入后更新 新的值
002,冲突不更新操作
数据不做任何变化
来自 《postgres 实战》
人生就像一滴水,非要落下才后悔!
--kingle