且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检测行是否已更新或插入

更新时间:2023-12-04 17:36:10

您可以查看系统列 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