我在另一张表中有大约88k的记录,比如ac。我想将表ac的一列更新为主表,如tbl。例如 - 表tbl样本记录如
col1 col2 col3 col4
abc dhj 123 ab12
def bhv 456 ds34
ghi hwj 789 hj46
jkl yuh 012 ke28
在表ac样本记录中
col1 col3`
cba 123
fed 456
ihg 789
lkj 012
如何从ac表更新tbl值。所以记录看起来像
col1 col2 col3 col4
cba dhj 123 ab12
fed bhv 456 ds34
ihg hwj 789 hj46
lkj yuh 012 ke28
你可以做一个correlated update:
update tbl
set col1 = (select col1 from ac where ac.col3 = tbl.col3)
where exists (select col1 from ac where ac.col3 = tbl.col3);
3 rows updated.
select * from tbl;
COL1 COL2 COL3 COL4
---- ---- ---- ----
cba dhj 123 ab12
fed bhv 456 ds34
ihg hwj 789 hj46
jkl yuh 012 ke28
或者merge:
merge into tbl
using ac
on (ac.col3 = tbl.col3)
when matched then update set tbl.col1 = ac.col1;
3 rows merged.
select * from tbl;
COL1 COL2 COL3 COL4
---- ---- ---- ----
cba dhj 123 ab12
fed bhv 456 ds34
ihg hwj 789 hj46
jkl yuh 012 ke28
在这两种情况下,第四行都没有受到影响,因为ac
中没有匹配的记录,正如@Littlefoot指出的那样。 merge
没有找到匹配;对于update
版本,如果没有要更新的matchign行,则where exists
子句会阻止将值设置为null。如果ac
中的第四行是012
而不是210
,则两个版本都会更新。