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

Posted 程序媛一枚~

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

参考

以上是关于Postgresql on conflict do update 设置当前值,原始值,当前值与原始值相加值的主要内容,如果未能解决你的问题,请参考以下文章

postgresql ON CONFLICT ON CONSTRAINT 用于 2 个约束

如何在 PostgreSQL 中使用 RETURNING 和 ON CONFLICT?

Postgresql insert on conflict笔记

PostgreSQL INSERT ON CONFLICT UPDATE (upsert) 使用所有排除值

ON CONFLICT DO UPDATE 缺少 FROM 子句

在 clickhouse 上类似 ON CONFLICT DO NOTHING