如何使用 Oracle SQL 中的相同子查询更新同一 table 中的多个列
How to update multiple columns in the same table with the same sub-query in Oracle SQL
在 Oracle 中是否有更好的方法来编写这种通用类型更新:
UPDATE table1
SET c1 = ( SELECT d1 FROM table2 WHERE table1.id = table2.id ),
c2 = ( SELECT d2 FROM table2 WHERE table1.id = table2.id )
以上更新只是一个例子。 sub-select 可能要复杂得多。
我看到其他 SQL 方言有 UPDATE ... SET ... FROM,但这在 Oracle 中似乎没有。
您可以一次更新多个列:
drop table t1;
drop table t2;
create table t1 (col1 number, col2 number, col3 number);
create table t2 (col1 number, col2 number, col3 number);
insert into t1 values (1, 10, 100);
insert into t1 values (2, 20, 200);
insert into t2 values (1, 100, 1000);
insert into t2 values (2, 200, 2000);
commit;
update t1
set (col2, col3) = (select col2, col3 from t2 where t2.col1 = t1.col1);
commit;
select * from t1;
COL1 COL2 COL3
---------- ---------- ----------
1 100 1000
2 200 2000
在 Oracle 中是否有更好的方法来编写这种通用类型更新:
UPDATE table1
SET c1 = ( SELECT d1 FROM table2 WHERE table1.id = table2.id ),
c2 = ( SELECT d2 FROM table2 WHERE table1.id = table2.id )
以上更新只是一个例子。 sub-select 可能要复杂得多。
我看到其他 SQL 方言有 UPDATE ... SET ... FROM,但这在 Oracle 中似乎没有。
您可以一次更新多个列:
drop table t1;
drop table t2;
create table t1 (col1 number, col2 number, col3 number);
create table t2 (col1 number, col2 number, col3 number);
insert into t1 values (1, 10, 100);
insert into t1 values (2, 20, 200);
insert into t2 values (1, 100, 1000);
insert into t2 values (2, 200, 2000);
commit;
update t1
set (col2, col3) = (select col2, col3 from t2 where t2.col1 = t1.col1);
commit;
select * from t1;
COL1 COL2 COL3
---------- ---------- ----------
1 100 1000
2 200 2000