支持 RETURNING 子句,可以返回新增、更新或者删除的数据行;
支持 WHEN NOT MATCHED BY SOURCE 操作,用于操作源表中不存在但是目标表中存在的数据行。
RETURNING 子句
CREATE TABLE test (
id INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
tag VARCHAR(10) NOT NULL UNIQUE,
posts INT NOT NULL DEFAULT 0
);
MERGE INTO test t
USING (VALUES ('pg17')) AS s(tag)
ON t.tag = s.tag
WHEN MATCHED THEN
UPDATE SET posts = posts + 1
WHEN NOT MATCHED THEN
INSERT (tag, posts) VALUES (s.tag, 1)
RETURNING *;
tag | id | tag | posts
--------+----+----------+-------------
pg17 | 1 | pg17 | 1
MERGE INTO test t
USING (VALUES ('pg17')) AS s(tag)
ON t.tag = s.tag
WHEN MATCHED THEN
UPDATE SET posts = posts + 1
WHEN NOT MATCHED THEN
INSERT (tag, posts) VALUES (s.tag, 1)
RETURNING *;
tag | id | tag | posts
--------+----+----------+-------------
pg17 | 1 | pg17 | 2
MERGE INTO test t
USING (VALUES ('pg17')) AS s(tag)
ON t.tag = s.tag
WHEN MATCHED THEN
UPDATE SET posts = posts + 1
WHEN NOT MATCHED THEN
INSERT (tag, posts) VALUES (s.tag, 1)
RETURNING t.*;
id | tag | posts
----+----------+-------------
1 | pg17 | 2
MERGE INTO test t
USING (VALUES ('sql'),('pg17')) AS s(tag)
ON t.tag = s.tag
WHEN MATCHED THEN
UPDATE SET posts = posts + 1
WHEN NOT MATCHED THEN
INSERT (tag, posts) VALUES (s.tag, 1)
RETURNING t.*, merge_action();
id | tag | posts | merge_action
----+----------+-------------+--------------
2 | sql | 1 | INSERT
1 | pg17 | 4 | UPDATE
WHEN NOT MATCHED BY SOURCE
MERGE INTO test t
USING (VALUES ('pg17')) AS s(tag)
ON t.tag = s.tag
WHEN MATCHED THEN
UPDATE SET posts = posts + 1
WHEN NOT MATCHED THEN
INSERT (tag, posts) VALUES (s.tag, 1)
WHEN NOT MATCHED BY SOURCE THEN
DELETE;
SELECT * FROM test;
id | username | touch_count
----+----------+-------------
1 | pg17 | 5