表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。


当前回答

这就是所谓的相关更新

UPDATE table1 t1
   SET (name, desc) = (SELECT t2.name, t2.desc
                         FROM table2 t2
                        WHERE t1.id = t2.id)
 WHERE EXISTS (
    SELECT 1
      FROM table2 t2
     WHERE t1.id = t2.id )

假设连接的结果是键保留视图,您也可以这样做

UPDATE (SELECT t1.id, 
               t1.name name1,
               t1.desc desc1,
               t2.name name2,
               t2.desc desc2
          FROM table1 t1,
               table2 t2
         WHERE t1.id = t2.id)
   SET name1 = name2,
       desc1 = desc2

其他回答

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;

试试这个:

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;
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工作表上运行它的确切方式。他们说这很慢,但这是我处理这个案子的唯一办法。

下面似乎是一个更好的答案,使用'in'子句,允许多个键的连接:

update fp_active set STATE='E', 
   LAST_DATE_MAJ = sysdate where (client,code) in (select (client,code) from fp_detail
  where valid = 1) ...

完整的例子如下: http://forums.devshed.com/oracle-development-96/how-to-update-from-two-tables-195893.html -从网络档案,因为链接已死。

问题在于,在'in'之前的where子句的括号中有你想用作键的列,在括号中有相同的列名的select语句。 where (columnn1,column2) in (select (columnn1,column2) from table where I want的set);

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);