--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