如何更新另一个表中的记录

问题描述 投票:0回答:1

我在另一张表中有大约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
sql oracle
1个回答
2
投票

你可以做一个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,则两个版本都会更新。

© www.soinside.com 2019 - 2024. All rights reserved.