【问题标题】:Update with Join query in Oracle在 Oracle 中使用 Join 查询进行更新
【发布时间】:2011-10-07 17:07:12
【问题描述】:

查询有什么问题? (无限期执行)

UPDATE table1 t1 SET (t1.col,t1.Output) = (
  SELECT t2.col, t3.Output + t2.col
  FROM tabl2 t3 
  LEFT JOIN table1 t2 ON t3.Join_Key = t2.Join_Key
  WHERE t2.col is not NULL);

请帮帮我。

【问题讨论】:

  • “无限期执行”是什么意思?它没有完成,没有解析,更新不一致的行还是什么?
  • 另外,你能用简单的英语解释一下你的意思是什么吗?您现在的子查询不相关,如果返回多行,更新将失败。

标签: sql oracle sql-update oracle10g


【解决方案1】:

除非您的 SELECT 子查询返回单行,否则您的 UPDATE 语句应该会失败并出现错误

ORA-01427: single-row subquery returns more than one row

通常,如果您有相关更新,则需要一些条件将外部表 T1 中的行与内部子查询中的行相关联,以确保子查询返回单行。这通常看起来像

UPDATE table1 t1 SET (t1.col,t1.Output) = (
  SELECT t2.col, t3.Output + t2.col
  FROM tabl2 t3 
  LEFT JOIN table1 t2 ON t3.Join_Key = t2.Join_Key
  WHERE t2.col is not NULL
    AND t1.some_key = t2.some_key);

最后,这个UPDATE 语句正在更新T1 中的每一行。那是你的意图吗?还是您只想更新例如在子查询中找到匹配项的行?

【讨论】:

  • 是的,我需要在子查询中找到匹配项
  • 是你的update语句更新了table1中的所有记录。因为 UPDATE table1 没有 WHERE 子句
【解决方案2】:

对于通用 table1、table2 和 join_key 引用,您的查询没有多大意义。

如果这不是您要查找的内容,那么拥有一些示例数据有助于更好地了解您要查找的结果。

update table1 t1
   set t1.col = (select t2.col
                 from table2 t2
                 where  t1.join_key = t2.join_key(+)  
                  and  t1.col is not null),
       t1.output = (select t2.output + t1.col
                    from  table2 t2
                   where  t1.join_key = t2.join_key(+)  
                     and  t1.col is not null);

【讨论】:

    猜你喜欢
    • 2013-05-24
    • 1970-01-01
    • 2014-03-16
    • 2012-08-29
    • 1970-01-01
    • 1970-01-01
    • 2014-07-27
    • 2014-03-13
    • 1970-01-01
    相关资源
    最近更新 更多