使用单个选择的值更新多个列

时间:2014-01-27 14:30:23

标签: oracle sql-update

现在我有这样的事情:

UPDATE TableA
SET a  = (SELECT b FROM TableB),
    aa = (SELECT b FROM TableB)

有更优雅的解决方案吗?

2 个答案:

答案 0 :(得分:2)

你可以写:

UPDATE TableA
SET (a, aa) = (SELECT b, b FROM TableB);

注意:这假设TableB只包含一行。如果没有,将引发异常。

答案 1 :(得分:0)

使用另一个表中的值更新一个表时要小心,否则即使您认为只更新了几行,也会更新目标表中的所有行。在大型表格上,这将非常痛苦(并破坏您的数据)。例如:

update tab_x x
set (col2, col3) = (
    select col2, col3
    from tab_y y
    where x.col1 = y.col1)
-- the following part will make sure we only update rows
-- that match the join condition (x.col1 = y.col1)
-- without this part, we'd update all rows in the x table!
where exists (
    select 1
    from tab_y y
    where x.col1 = y.col1
)

完整的例子是:

SQL> set display on
SQL> drop table tab_x
Table dropped.
SQL> create table tab_x
(
col1 number,
col2 varchar2(20),
col3 varchar2(20)
)
Table created.
SQL> drop table tab_y
Table dropped.
SQL> create table tab_y
(
col1 number,
col2 varchar2(20),
col3 varchar2(20)
)
Table created.
SQL> insert into tab_x values (1, 'Col2 from x','Col3 from x')
1 row created.
SQL> insert into tab_x values (2, 'Col2 from x','Col3 from x')
1 row created.
SQL> insert into tab_x values (3, 'Col2 from x','Col3 from x')
1 row created.
SQL> insert into tab_y values (1, 'Col2 from y','Col3 from y')
1 row created.
SQL> insert into tab_y values (2, 'Col2 from y','Col3 from y')
1 row created.
SQL> insert into tab_y values (9, 'Col2 from y','Col3 from y')
1 row created.
SQL> commit
Commit complete.
SQL> select * from tab_x

      COL1 COL2                 COL3                
---------- -------------------- --------------------
         1 Col2 from x          Col3 from x         
         2 Col2 from x          Col3 from x         
         3 Col2 from x          Col3 from x         

3 rows selected.
SQL> update tab_x x
set (col2, col3) = (
    select col2, col3
    from tab_y y
    where x.col1 = y.col1)
-- the following part will make sure we only update rows
-- that match the join condition (x.col1 = y.col1)
-- without this part, we'd update all rows in the x table!
where exists (
    select 1
    from tab_y y
    where x.col1 = y.col1
)
2 rows updated.
SQL> select * from tab_x

      COL1 COL2                 COL3                
---------- -------------------- --------------------
         1 Col2 from y          Col3 from y         
         2 Col2 from y          Col3 from y         
         3 Col2 from x          Col3 from x         

3 rows selected.