检测行是否已更新或插入

检测行是否已更新或插入

问题描述:

我正在使用 ON CONFLICT 进行 INSERT 来使用Java进行postgre。有什么方法可以找出 executeUpdate 是插入行还是更新行?

I am doing an INSERT with ON CONFLICT to postgre using java. Is there any way to find out if the executeUpdate inserted the row or updated it?

您可以查看系统列 xmax 来说明区别。在这种情况下,插入行的价格为 0

CREATE TABLE tbl(id int PRIMARY KEY, col int);
INSERT INTO tbl VALUES (1, 1);



INSERT INTO tbl(id, col)
VALUES (1,11), (2,22)
ON     CONFLICT (id) DO UPDATE
SET    col = EXCLUDED.col
RETURNING *, (xmax = 0) AS inserted;

这是基于未记录的实现细节,在将来的版本中可能会更改(即使不太可能)。它适用于Postgres 9.5和9.6。

This is building on an undocumented implementation detail that might change in future releases (even if unlikely). It works for Postgres 9.5 and 9.6.

它的优点:您无需引入其他列。

The beauty of it: you do not need to introduce additional columns.

详细说明:

  • PostgreSQL Upsert differentiate inserted and updated rows using system columns XMIN, XMAX and others