Postgresql on conflict do update 设置当前值,原始值,当前值与原始值相加值

Postgresql插入时主键冲突会报错,可采取冲突不做任何处理或者进行更新——俩种方式避免报错;更新时可以保存新值,保存新值与旧值表达式。

更新时可以保存原来的值,ON CONFLICT(date,city) DO NOTHING; 或者 ON CONFLICT ON CONSTRAINT distributors_pkey DO NOTHING;
保存当前的值 ON CONFLICT (did) DO UPDATE
SET dname = EXCLUDED.dname;

保存旧值与新值的表达式,比如拼接, ON CONFLICT (did) DO UPDATE
SET dname = EXCLUDED.dname || ’ (formerly ’ || d.dname || ‘)’

  • INSERT INTO distributors (did, dname) VALUES (9, ‘Antwerp Design’)
    ON CONFLICT(date,city) DO NOTHING;
  • INSERT INTO distributors (did, dname) VALUES (9, ‘Antwerp Design’)
    ON CONFLICT ON CONSTRAINT distributors_pkey DO NOTHING;
  • INSERT INTO distributors AS d (did, dname) VALUES (8, ‘Anvil Distribution’)
    ON CONFLICT (did) DO UPDATE SET dname = EXCLUDED.dname
    WHERE d.zipcode <> ‘21201’;
  • INSERT INTO distributors AS d (did, dname) VALUES (8, ‘Anvil Distribution’)
    ON CONFLICT (did) DO UPDATE SET dname = EXCLUDED.dname || ’ (formerly ’ || d.dname || ‘)’
    WHERE d.zipcode <> ‘21201’;

sql源码

-- 日期序列
select generate_series('2022-07-09'::date,'2022-08-08'::date,'1 day')::date

-- 构建插入的表格数据
SELECT *
FROM ROWS FROM
    (
        json_to_recordset('[{"a":40,"b":"foo"},{"a":"100","b":"bar"}]')
            AS (a INTEGER, b TEXT),
        generate_series(1, 3)
    ) AS x (p, q, s)
ORDER BY p;

DROP TABLE IF EXISTS weather2;
CREATE TABLE IF NOT EXISTS weather2 (
    city            varchar(80),
    temp_lo         int,           -- 最低温度
    temp_hi         int,           -- 最高温度
    prcp            real,          -- 湿度
    date            date
);
ALTER TABLE weather2 ADD CONSTRAINT date_uniq UNIQUE (date, city); 

insert into weather2 as tos (city,temp_lo,date) SELECT p,q,s::date
FROM ROWS FROM
    (
		json_to_recordset('[{"a":40,"b":"sh"},{"a":"100","b":"qd"},{"a":"10","b":"qdd"},{"a":"3","b":"bj"}]')
            AS (b TEXT,a INTEGER),
        generate_series(1, 4),
		generate_series('2022-08-06'::date,'2022-08-09'::date,'1 day')
    ) AS x (p,q,r,s)
-- ORDER BY p
-- on conflict(date, city) do update set temp_lo = excluded.temp_lo; --保留当前要新插入的值
-- on conflict(date, city) do update set temp_lo = tos.temp_lo; --保留原始值
-- on conflict(date, city) do nothing; --保留原始值
on conflict(date, city) do update set temp_lo = tos.temp_lo+excluded.temp_lo; -- 原始值与当前值相加

select * from weather2

参考

  • http://postgres.cn/docs/12/sql-altertable.html

你可能感兴趣的:(数据库,Postgresql,JAVA,postgresql,数据库,sql,on,conflict)