【问题标题】:Oracle : update column depending on column from another tableOracle:根据另一个表中的列更新列
【发布时间】:2017-09-09 12:19:54
【问题描述】:

我有两张桌子:

A 列是我们将在其上进行连接的列。我需要更新:

B = if(D not null) then D
    else C

我试过这个:

update Tab1 x
set B = case when
      (select D from Tab2 t2
      inner join Tab1 t1
      on t1.A = t2.A
      where t1.A = x.A) is not null 
then (select D from Tab2 t2
      inner join Tab1 t1
      on t1.A = t2.A
      where t1.A = x.A)
else x.D END
where x.A > (user_input) and x.A <= (user_input)

这给了我输出:0 行更新。

另外,作为说明,我需要在一个更新语句本身中执行此操作。表 Tab1 中还有其他非依赖列将在同一更新中更新。

我知道这看起来很混乱,两次执行相同的 select 子查询根本没有优化,但我并不真正了解如何实现这一点。

感谢任何帮助或指点!

【问题讨论】:

    标签: oracle sql-update case


    【解决方案1】:

    我认为MERGE 是进行多表更新的最佳方法:

    merge into tab1 t1
    using tab2 t2
    on (
        t1.a = t2.a
        and t1.a between 1 and 10  -- change this as needed
    )
    when matched then
        update set t1.b = coalesce(t2.d, t1.c);
    

    【讨论】:

      【解决方案2】:

      应该是这样的

      update Tab1 t1
      set t1.B = nvl((select t2.d from Tab2 t2 where t2.a = t1.a), t1.c)
      where t1.a = :user_input
      

      顺便说一句,0 rows updated 与更新中的 where 条件有关。似乎它与表 Tab1 中的任何记录都不匹配 - 因为,您的语句 where x.A &gt; (user_input) and x.A &lt;= (user_input) 将始终评估为 false

      【讨论】:

        【解决方案3】:
        merge into tab1 t1
        using tab2 t2
        on (    t1.a = t2.a)
        when matched then
            update set t1.b = case when t2.d is not null then t2.d else  t1.c end
        ;
        

        【讨论】:

          猜你喜欢
          • 2017-07-24
          • 2011-11-25
          • 2019-08-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-02-19
          • 1970-01-01
          相关资源
          最近更新 更多