通过内部查询更新Oracle中的表

问题描述

我有以下查询,该查询在Sybase中有效,我需要帮助为Oracle重写它。 我是Oracle新手。

update table1 
set col1 = (select sum(col3) from table2 t2 where t2.id = t1.id and t2.col <> 'on')
from table1 t1 
where t1.id > 1 and t1.col5 in (12,13) and exists 
(select id from table2 t2 where t2.id = t1.id and t2.col <> 'on' and col3 > 0)

当我尝试在Oracle中执行时,我遇到了表达式错误

解决方法

在Oracle中,您不能这样使用From子句:

Oracle中有三个选项可基于另一个表更新表:

将其更新为更新视图

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

通过编写子查询(即相关的更新)进行更新

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 )

使用Merge语句更新而不插入:

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;

下面是Oracle官方更新documentation

以上示例摘自此post

,

这对我有用

 update table1 t1
 set t1.col1 = (select sum(col3) from table2 t2 where t2.id = t1.id and t2.col <> 'on')
 where t1.id > 1 and t1.col5 in (12,13) and exists 
 (select id from table2 t2 where t2.id = t1.id and t2.col <> 'on' and col3 > 0)