Oracle SQL:用另一个表的数据更新一个表

表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的namedesc使用相同的id?所以最终的结果是

表1:

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

Question来自用来自另一个表的数据更新一个表,但专门用于oracle SQL。

1242541 次浏览

试一试

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

这里似乎有一个更好的答案,使用'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 -从web存档,因为链接已死 问题是,在'in'前面的where子句的括号中有你想用作键的列,在括号中有相同的列名的select语句。 where (column1, column2) in (select (column1, column2) from table where " set I want");

如果你的表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, ...
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;

试试这个:

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;