如何将带有“NOT MATCHED BY TARGET”的 MERGE 语句从 MS SQL 更正迁移到 PostgreSQL?
How to correct migrate MERGE statement with " NOT MATCHED BY TARGET " from MS SQL to PostgreSQL?
我有这样的sql声明:
MERGE pvl.testTable AS T
USING temp.testTable AS S
ON (T.Id = S.ID)
WHEN NOT MATCHED BY TARGET THEN
INSERT (first,
second,
third,
fourth) VALUES (s.first,
s.second,
s.third,
s.fourth)
WHEN MATCHED
THEN
UPDATE
SET
T.first = S.first,
T.second = S.second,
T.third = S.third,
T.fourth = S.fourth
WHEN NOT MATCHED BY SOURCE
THEN
DELETE;
另外我知道我必须使用 ON CONFLICT,但是我如何处理 WHEN NOT MATCHED BY TARGET 和 WHEN NOT MATCHED BY SOURCE?
您可以分两步完成:1. 更新插入和 2. 删除
-- Perform upsert and return all inserted/updated ids
WITH upsert(id) AS
(
INSERT INTO target_table (first, second, third, fourth)
SELECT first, second, third, fourth FROM source_table
ON CONFLICT (id) DO UPDATE SET
first = excluded.first,
second = excluded.second,
third = excluded.third,
fourth = excluded.fourth
RETURNING id
)
-- Delete any records in target that aren't in source table
DELETE FROM target_table
WHERE id NOT IN (SELECT id FROM upsert);
我有这样的sql声明:
MERGE pvl.testTable AS T
USING temp.testTable AS S
ON (T.Id = S.ID)
WHEN NOT MATCHED BY TARGET THEN
INSERT (first,
second,
third,
fourth) VALUES (s.first,
s.second,
s.third,
s.fourth)
WHEN MATCHED
THEN
UPDATE
SET
T.first = S.first,
T.second = S.second,
T.third = S.third,
T.fourth = S.fourth
WHEN NOT MATCHED BY SOURCE
THEN
DELETE;
另外我知道我必须使用 ON CONFLICT,但是我如何处理 WHEN NOT MATCHED BY TARGET 和 WHEN NOT MATCHED BY SOURCE?
您可以分两步完成:1. 更新插入和 2. 删除
-- Perform upsert and return all inserted/updated ids
WITH upsert(id) AS
(
INSERT INTO target_table (first, second, third, fourth)
SELECT first, second, third, fourth FROM source_table
ON CONFLICT (id) DO UPDATE SET
first = excluded.first,
second = excluded.second,
third = excluded.third,
fourth = excluded.fourth
RETURNING id
)
-- Delete any records in target that aren't in source table
DELETE FROM target_table
WHERE id NOT IN (SELECT id FROM upsert);