[英]Merge statement with two conditions in same CLAUSE alternative in Postgres
I am facing issue while migration of Oracle Merge into Postgres using WITH Clause. 使用WITH子句将Oracle Merge迁移到Postgres时遇到问题。
Below is the example code from ORACLE: 下面是来自ORACLE的示例代码:
SELECT * FROM source;
ID STATUS DESCRIPTION
---------- ---------- -----------------------
1 20 Description of level 1
2 10 Description of level 2
3 20 Description of level 3
4 10 Description of level 4
5 20 Description of level 5
Destination table is below: 目标表如下:
SELECT * FROM destination;
1 20 Description of level 1
2 10 Description of level 2
3 20 Description of level 3
4 10 Description of level 4
5 20 Description of level 5
6 10 Description of level 6
7 20 Description of level 7
8 10 Description of level 8
9 20 Description of level 9
10 10 Description of level 10
I have Merge implementation in ORACLE like below: When merged : 我在ORACLE中具有Merge实现,如下所示:合并时:
MERGE INTO destination d
USING source s
ON (s.id = d.id)
WHEN MATCHED THEN
UPDATE SET d.description = 'Updated'
DELETE WHERE d.status = 10;
5 rows merged.
SELECT * FROM destination;
ID STATUS DESCRIPTION
---------- ---------- -----------------------
1 20 Updated
3 20 Updated
5 20 Updated
6 10 Description of level 6
7 20 Description of level 7
8 10 Description of level 8
9 20 Description of level 9
10 10 Description of level 10
8 rows selected.
I was able to convert a Merge which has one condition in both MATCHED & UNMATCHED clauses using CTE. 我可以使用CTE转换在MATCHED和UNMATCHED子句中都有一个条件的Merge。 But not sure how to do (both DELETE & UPDATE), if I have two conditions in the same clause. 但是,如果我在同一子句中有两个条件,则不确定该怎么做(DELETE和UPDATE)。
Edited: I understood the answer a_horse_with_no_name has shared. 编辑:我知道答案a_horse_with_no_name已共享。 But got confused whether I need to do a nested CTEs in the below case. 但是对于以下情况是否需要嵌套CTE感到困惑。
MERGE INTO destination d
USING source s
ON (s.id = d.id)
WHEN MATCHED THEN
UPDATE SET d.description = 'Updated'
DELETE WHERE d.status = 10
WHEN NOT MATCHED THEN
INSERT (ID, STATUS, DESCRIPTION) VALUES (s.id,s.status,s.description);
If my merge statement has NOT MATCHED too then how do I do it. 如果我的合并语句也未匹配,那么我该怎么做。
I am not sure if this is the most efficient way to do it, but it does what you want: 我不确定这是否是最有效的方法,但是它可以满足您的要求:
with updated as (
update destination d
set description = 'Updated'
from source s
where s.id = d.id
and d.status <> 10
returning d.id
)
delete from destination
where id not in (select id from updated)
and exists (select *
from source s
where s.id = destination.id);
It first updates rows in destination
that exist in source
and have a status other than 10. Then it deletes those that were not updated and exist in the source
table. 它首先更新destination
中source
中存在且状态非10的行,然后删除source
表中未更新但存在的那些行。
Online example: http://rextester.com/KTTOX89581 在线示例: http : //rextester.com/KTTOX89581
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.