【问题标题】:Updating a table in Oracle by inner query通过内部查询更新 Oracle 中的表
【发布时间】:2020-12-16 09:08:25
【问题描述】:

我有以下查询,它在 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 中执行时,出现缺少表达式错误

【问题讨论】:

标签: sql oracle join sql-update


【解决方案1】:

在 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

【讨论】:

  • 当我尝试通过写子查询进行更新时,即相关更新,它会继续执行
  • 能否请您使用相关查询更新您的问题并解释逻辑,如果可能的话分享一些示例数据。
【解决方案2】:

这对我有用

 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-16
    • 2018-05-22
    • 2018-12-08
    • 1970-01-01
    • 1970-01-01
    • 2017-07-18
    • 2015-09-02
    • 1970-01-01
    相关资源
    最近更新 更多