使用另一个表中的值更新一个表

时间:2019-11-22 06:00:32

标签: oracle sql-update

抱歉,这个非常基础的新手数据库问题...

我有两个具有相同列的表,但想用第二个表中相应列的值替换第一个表中一个列的值。

即table1:姓名,年龄table2:姓名,年龄

每个表具有相同的“名称”值,只是具有不同的年龄。

从算法上来说:对于表1中的每一行,在表2中找到具有相同名称的行,并使table1.age = table2.age

数据库是Oracle。我尝试过类似的

update table1 set table1.age = (select table2.age where table2.name = table1.name)

认为如果需要的话,它可能会执行隐式联接,但是没有运气。我也尝试过明确地进行内部连接,但没有运气。

谢谢!

3 个答案:

答案 0 :(得分:4)

MERGE通常比标量子查询快

merge into table1 t1
using table2 t2 on (t1.name = t2.name)
when matched then update
  set age = t2.age;

答案 1 :(得分:1)

尝试使用pl / sql循环:

begin 
for t2 in (
    select name, age
    from table2
    )
loop
    update table1 t1
    set t1.age=t2.age where t1.name = t2.name; 
end loop;
end;

尽管如此,它根本没有效率。

答案 2 :(得分:1)

除了子查询中的from子句,您什么都不会错过:

update table1 t1
   set t1.age =
       (select t2.age 
          from table2 t2
         where trim(t2.name) = trim(t1.name) )

并使用trim()可以防止字符串类型值周围的(前导和尾随)空格。