如果匹配,则在表中添加具有另一个值的列

时间:2021-05-07 10:23:13

标签: sql oracle

我有两张桌子:

表 1

<头>
A B C
A1 B1 C1
A2 B2 C2
A3 B3 C3
A4 B4 C4
A5 B5 C5
A6 B6 C6

table2

<头>
A D
A1 D1
A3 D3
A5 D5
A6 D6

我想用 D 列更新表 1,该列显示 D 列中由 A 连接的值。但是,正在更改表 1 添加列 D,然后合并两个表并在匹配时更新有没有更好的办法?

1 个答案:

答案 0 :(得分:0)

您可以在需要时join 中的值:

select t1.*, t2.d
from table1 t1 left join
     table2 t2
     on t1.a = t2.a;

如果这还不够,您可以添加该列:

alter table1 add d <type>;

然后你可以更新它:

update table1 t1
    set d = (select t2.d from table2 t2 where t2.a = t1.a)
    where exists (select t2.d from table2 t2 where t2.a = t1.a);
相关问题