在 PostgreSQL 中重复更新时插入? [英] Insert, on duplicate update in PostgreSQL?
问题描述
几个月前,我从 Stack Overflow 上的一个答案中了解到如何使用以下语法在 MySQL 中一次执行多个更新:
Several months ago I learned from an answer on Stack Overflow how to perform multiple updates at once in MySQL using the following syntax:
INSERT INTO table (id, field, field2) VALUES (1, A, X), (2, B, Y), (3, C, Z)
ON DUPLICATE KEY UPDATE field=VALUES(Col1), field2=VALUES(Col2);
我现在已经切换到 PostgreSQL,显然这不正确.它指的是所有正确的表,所以我认为这是使用不同关键字的问题,但我不确定 PostgreSQL 文档中的哪个位置.
I've now switched over to PostgreSQL and apparently this is not correct. It's referring to all the correct tables so I assume it's a matter of different keywords being used but I'm not sure where in the PostgreSQL documentation this is covered.
为了澄清,我想插入一些东西,如果它们已经存在,就更新它们.
To clarify, I want to insert several things and if they already exist to update them.
推荐答案
PostgreSQL 自 9.5 版起具有 UPSERT 语法,带有 ON CONFLICT 子句. 使用以下语法(类似于 MySQL)
PostgreSQL since version 9.5 has UPSERT syntax, with ON CONFLICT clause. with the following syntax (similar to MySQL)
INSERT INTO the_table (id, column_1, column_2)
VALUES (1, 'A', 'X'), (2, 'B', 'Y'), (3, 'C', 'Z')
ON CONFLICT (id) DO UPDATE
SET column_1 = excluded.column_1,
column_2 = excluded.column_2;
<小时>
在 postgresql 的电子邮件组档案中搜索upsert"导致找到 在手册中做你可能想做的事的例子:
示例 38-2.UPDATE/INSERT 异常
此示例使用异常处理来执行 UPDATE 或 INSERT,视情况而定:
This example uses exception handling to perform either UPDATE or INSERT, as appropriate:
CREATE TABLE db (a INT PRIMARY KEY, b TEXT);
CREATE FUNCTION merge_db(key INT, data TEXT) RETURNS VOID AS
$$
BEGIN
LOOP
-- first try to update the key
-- note that "a" must be unique
UPDATE db SET b = data WHERE a = key;
IF found THEN
RETURN;
END IF;
-- not there, so try to insert the key
-- if someone else inserts the same key concurrently,
-- we could get a unique-key failure
BEGIN
INSERT INTO db(a,b) VALUES (key, data);
RETURN;
EXCEPTION WHEN unique_violation THEN
-- do nothing, and loop to try the UPDATE again
END;
END LOOP;
END;
$$
LANGUAGE plpgsql;
SELECT merge_db(1, 'david');
SELECT merge_db(1, 'dennis');
<小时>
WITH foos AS (SELECT (UNNEST(%foo[])).*)
updated as (UPDATE foo SET foo.a = foos.a ... RETURNING foo.id)
INSERT INTO foo SELECT foos.* FROM foos LEFT JOIN updated USING(id)
WHERE updated.id IS NULL;
请参阅a_horse_with_no_name 的答案以获得更清晰的示例.
See a_horse_with_no_name's answer for a clearer example.
这篇关于在 PostgreSQL 中重复更新时插入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!