更新多个列,其中值来自不同的表 - Oracle

时间:2017-01-13 18:58:51

标签: sql oracle sql-update dml

我需要更新同一个表中的多个列。但是,我需要更新的值来自不同的表。我目前将更新语句分开。问题是我有很多列要更新并运行许多更新语句会导致许多锁和性能问题。

有什么方法可以将它们合并到一个更新语句中? 这是我现在的更新语句列表中的两个示例:

  UPDATE table1 t1
     SET t1.col1 = (
            SELECT col7
              FROM table1 t1b, table2 t2
             WHERE t1b.col2 = t2.col2
               AND t1b.col3 = t2.col3
               AND t1b.col2 = t1.col2)
   WHERE t1.col4 = 0
     AND t1.col2 IN (SELECT col2 FROM table2);


  UPDATE table1 t1
     SET t1.col5 = (
            SELECT col6
              FROM table1 t1c, table3 t3
             WHERE t1c.col2 = t3.col2
               AND t1c.col3 = t3.col3
               AND t1c.col2 = t1.col2 )
   WHERE t1.col4 = 0
     AND t1.col2 IN (SELECT col2 FROM table3);

1 个答案:

答案 0 :(得分:1)

MERGE应该这样做:

merge into table1 tg
using (
  SELECT t1.col2, t1.col3, 
         col7 
         col6
  FROM table1 t1
    JOIN table2 t2 ON t1.col2 = t2.col2
                  AND t1.col3 = t2.col3
    JOIN table3 t3 ON t1.col2 = t3.col2
                  AND t1.col3 = t3.col3
) x ON (x.col2 = tg.col2 and x.col3 = tg.col3)
when matched then update
   set col1 = x.col7, 
       col5 = x.col6;

请注意,这与您的语句略有不同,因为它假定连接到table2和table3都成功。如果不是这种情况,则将(内部)连接更改为左(外)连接。

相关问题