表1:

id    name    desc
-----------------------
1     a       abc
2     b       def
3     c       adf

表2:

id    name    desc
-----------------------
1     x       123
2     y       345

在oracle SQL中,我如何运行一个SQL更新查询,可以更新表1与表2的名称和desc使用相同的id?所以最终的结果是

表1:

id    name    desc
-----------------------
1     x       123
2     y       345
3     c       adf

问题是从更新一个表从另一个数据,但特别为oracle SQL。


当前回答

try

UPDATE Table1 T1 SET
T1.name = (SELECT T2.name FROM Table2 T2 WHERE T2.id = T1.id),
T1.desc = (SELECT T2.desc FROM Table2 T2 WHERE T2.id = T1.id)
WHERE T1.id IN (SELECT T2.id FROM Table2 T2 WHERE T2.id = T1.id);

其他回答

试试这个:

MERGE INTO table1 t1
USING
(
-- For more complicated queries you can use WITH clause here
SELECT * FROM table2
)t2
ON(t1.id = t2.id)
WHEN MATCHED THEN UPDATE SET
t1.name = t2.name,
t1.desc = t2.desc;

如果你的表t1和它的备份t2有很多列,这是一种紧凑的方法。

此外,我的相关问题是,只有一些列被修改,许多行没有对这些列进行编辑,所以我想保留它们——基本上是从整个表的备份中恢复列的子集。如果只想恢复所有行,请跳过where子句。

当然,更简单的方法是删除和插入作为选择,但在我的情况下,我需要一个只有更新的解决方案。

诀窍在于,当您从一对具有重复列名的表中选择*时,第二个表将被命名为_1。这就是我想到的:

  update (
    select * from t1 join t2 on t2.id = t1.id
    where id in (
      select id from (
        select id, col1, col2, ... from t2
        minus select id, col1, col2, ... from t1
      )
    )
  ) set col1=col1_1, col2=col2_1, ...

try

UPDATE Table1 T1 SET
T1.name = (SELECT T2.name FROM Table2 T2 WHERE T2.id = T1.id),
T1.desc = (SELECT T2.desc FROM Table2 T2 WHERE T2.id = T1.id)
WHERE T1.id IN (SELECT T2.id FROM Table2 T2 WHERE T2.id = T1.id);
Update table set column = (select...)

从未为我工作,因为设置只期望1个值- SQL错误:ORA-01427:单行子查询返回多行。

下面是解决方案:

BEGIN
For i in (select id, name, desc from table1) 
LOOP
Update table2 set name = i.name, desc = i.desc where id = i.id;
END LOOP;
END;

这就是在SQLDeveloper工作表上运行它的确切方式。他们说这很慢,但这是我处理这个案子的唯一办法。

BEGIN
For i in (select id, name, desc from table2) 
LOOP
Update table1 set name = i.name, desc = i.desc where id = i.id and (name is null or desc is null);
END LOOP;
END;