使用merge:
merge into tbl1 tgt
using (select min(column1) column1, column2
from (select column1, column2 from tbl2 union all
select column1, column2 from tbl3)
group by column2) src
on (tgt.column2 = src.column2)
when matched then update set tgt.column1 = src.column1
假设您有这些表:
create table tbl1(column1, column2) as (
select 0, 'A' from dual union all
select 0, 'B' from dual union all
select 0, 'C' from dual union all
select 0, 'D' from dual );
create table tbl2(column1, column2) as (
select 1, 'A' from dual union all
select 41, 'D' from dual );
create table tbl3(column1, column2) as (
select 2, 'B' from dual union all
select 42, 'D' from dual );
我们在tbl2 中具有键A 的值,在tbl3 中具有B 的值,C 的值在两个源表中都不存在,并且键D 有两个有问题的值。您必须决定在最后一种情况下要做什么,对字符串使用任何聚合函数,如 min()、avg() 或 listagg()。如果这种情况不可能,那么您可以简化我的语句,用简单的联合替换源子查询。
您也可以使用update,但在这种情况下,您必须添加where 子句并检查键的存在以避免使值无效,这会使代码更长。
merge:的结果
COLUMN1 COLUMN2
---------- -------
1 A
2 B
0 C
41 D