![](/img/trans.png)
[英]Oracle SQL: Update a table with data from another columns of the same table
[英]Oracle SQL: Update a table with data from another table
表格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 更新查询,该查询可以使用表 2 的name
和desc
使用相同的id
更新表 1? 所以我得到的最终结果是
表格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
尝试这个:
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 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...)
从来没有为我工作,因为 set 只需要 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' 子句似乎是一个更好的答案,它允许join 有多个键:
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 - 来自 Z2567A54EC9705EB7AC2C 存档,因为 8 链接已死。
关键在于在“in”之前的 where 子句中将要用作括号中的键的列,并在括号中使用具有相同列名的 select 语句。 where ( column1,column2 ) in ( select ( column1,column2 ) from table where "the set I want" );
如果您的表 t1 和它的备份 t2 有很多列,那么这是一种紧凑的方法。
此外,我的相关问题是只有一些列被修改,许多行没有对这些列进行编辑,所以我想不理会这些列 - 基本上从整个表的备份中恢复列的子集。 如果您只想恢复所有行,请跳过 where 子句。
当然,更简单的方法是删除并插入为 select,但在我的情况下,我需要一个只需要更新的解决方案。
诀窍是,当您从一对具有重复列名的表中执行 select * 时,第二个将被命名为 _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, ...
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.