我正在更新 Postgres 8.4 数据库(来自 C# 代码),基本任务非常简单:更新现有行或插入新行(如果尚不存在)。通常我会这样做:
UPDATE my_table
SET value1 = :newvalue1, ..., updated_time = now(), updated_username = 'evgeny'
WHERE criteria1 = :criteria1 AND criteria2 = :criteria2
如果 0 行受到影响,则执行 INSERT:
INSERT INTO my_table(criteria1, criteria2, value1, ...)
VALUES (:criteria1, :criteria2, :newvalue1, ...)
不过,有一个轻微的变化。我不想更改 updated_time 和 updated_username 列,除非任何新值实际上与现有值不同,以避免在数据更新时间上误导用户。
如果我只进行更新,那么我也可以为值添加 WHERE 条件,但这在这里不起作用,因为如果数据库已经是最新的,更新将影响 0 行,然后我会尝试插入。
除了 SELECT 之外,还有 UPDATE 或 INSERT 之外,谁能想到一种优雅的方法来做到这一点?
I'm updating a Postgres 8.4 database (from C# code) and the basic task is simple enough: either UPDATE an existing row or INSERT a new one if one doesn't exist yet. Normally I would do this:
UPDATE my_table
SET value1 = :newvalue1, ..., updated_time = now(), updated_username = 'evgeny'
WHERE criteria1 = :criteria1 AND criteria2 = :criteria2
and if 0 rows were affected then do an INSERT:
INSERT INTO my_table(criteria1, criteria2, value1, ...)
VALUES (:criteria1, :criteria2, :newvalue1, ...)
There is a slight twist, though. I don't want to change the updated_time and updated_username columns unless any of the new values are actually different from the existing values to avoid misleading users about when the data was updated.
If I was only doing an UPDATE then I could add WHERE conditions for the values as well, but that won't work here, because if the DB is already up to date the UPDATE will affect 0 rows and then I would try to INSERT.
Can anyone think of an elegant way to do this, other than SELECT, then either UPDATE or INSERT?
发布评论
评论(7)
看一下 BEFORE UPDATE 触发器来检查并设置正确的值:
现在您甚至不必在 UPDATE 查询中提及字段 Updated_time,它将由触发器处理。
http://www.postgresql.org/docs/current/interactive/plpgsql -trigger.html
Take a look at a BEFORE UPDATE trigger to check and set the correct values:
Now you don't even have to mention the field updated_time in your UPDATE query, it will be handled by the trigger.
http://www.postgresql.org/docs/current/interactive/plpgsql-trigger.html
这里有两件事。
首先,根据数据库中的活动级别,您可能会在检查记录和将其插入另一个进程可能会临时创建该记录的位置之间遇到竞争条件。
该手册包含如何执行此操作的示例
链接示例
以避免这样做更新是suppress_redundant_updates_trigger()过程。要按照您希望的方式使用此功能,您必须有两个更新前触发器,第一个触发器将调用suppress_redundant_updates_trigger()以在未进行任何更改的情况下中止更新,第二个触发器将在进行更新时设置时间戳和用户名。触发器按字母顺序触发。
这样做还意味着更改上面示例中的代码,以便在更新之前先尝试插入。
抑制更新如何工作的示例:
Two things here.
Firstly depending on activity levels in your database you may hit a race condition between checking for a record and inserting it where another process may create that record in the interim.
The manual contains an example of how to do this
link example
To avoid doing an update there is the suppress_redundant_updates_trigger() procedure. To use this as you wish you wold have to have two before update triggers the first will call the suppress_redundant_updates_trigger() to abort the update if no change made and the second to set the timestamp and username if the update is made. Triggers are fired in alphabetical order.
Doing this would also mean changing the code in the example above to try the insert first before the update.
Example of how suppress update works:
Postgres 正在获得 UPSERT 支持。它目前位于 自 2015 年 5 月 8 日起(提交 ):
快照可供下载。它尚未发布版本。
Postgres is getting UPSERT support . It is currently in the tree since 8 May 2015 (commit):
A snapshot is available for download. It has not yet made a release.
插入表名(列列表)值(值列表)
ON CONFLICT 目标操作;
https://www.postgresqltutorial.com/postgresql-upsert/
虚拟示例:
INSERT INTO table_name(column_list) VALUES(value_list)
ON CONFLICT target action;
https://www.postgresqltutorial.com/postgresql-upsert/
Dummy example :
RETURNING
子句使您能够链接查询;第二个查询使用第一个查询的结果。 (在这种情况下是为了避免重新触摸相同的行)(自 postgres 8.4 起可使用 RETURNING)这里显示嵌入在 aa 函数中,但它也适用于普通 SQL
结果:
The
RETURNING
clause enables you to chain your queries; the second query uses the results from the first. (in this case to avoid re-touching the same rows) (RETURNING is available since postgres 8.4)Shown here embedded in a a function, but it works for plain SQL, too
RESULT:
这是一种根本不需要存储过程或触发器的方法。
Here is a method that doesn't require a stored procedure or trigger at all.
开始交易。使用 select 来查看要插入的数据是否已经存在,如果存在,则不执行任何操作,否则更新,如果不存在,则插入。最后关闭交易。
Start a transaction. Use a select to see if the data you'd be inserting already exists, if it does, do nothing, otherwise update, if it does not exist, then insert. Finally close the transaction.