【问题标题】:Oracle - update data in first table with rows from second tableOracle - 使用第二个表中的行更新第一个表中的数据
【发布时间】:2020-09-04 10:40:04
【问题描述】:

在 20/07/20 时如何使用 'modfied' (t2) 更新 'date_from' (t1)。

所以在这种情况下,在 t1 中,id 的 1 和 2 将被更新,id 3 保持不变。

表 1:

id    date_from
-----------------------
1     13/07/30
2     13/07/30
3     13/07/30

表 2:

id    name    modified
-----------------------
1     x       20/07/20
2     y       20/07/20
3     z       19/05/10

【问题讨论】:

    标签: sql oracle sql-update subquery


    【解决方案1】:

    类似这样的:

    update t1 a set
      a.date_from = (select b.modified
                     from t2 b
                     where b.id = a.id
                       and b.modified = date '2020-07-20'
                    )
    where exists (select null
                  from t2 c
                  where c.id = a.id
                    and c.modified = date '2020-07-20'
                 )
    

    【讨论】:

      【解决方案2】:

      如果速度很重要,那么

      merge into t1 trg
      using 
      (
          select  id, modified
          from    t2
          where   modified = date'2020-07-20'
      ) src
      on ( trg.id = src.id )
      when matched then update
      set trg.date_from = src.modified
      where lnnvl(trg.date_from = src.modified);
      

      【讨论】:

        【解决方案3】:

        您提前知道需要分配哪个值,因此您只需要筛选应该更新哪些行。 exists 似乎足够了:

        update t1 
        set date_from = date '2020-07-20'
        where exists (
            select 1 from t2 where t2.id = t1.id and t2.modified = date '2020-07-20'
        )
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-12
          • 1970-01-01
          • 2018-05-17
          • 2022-01-22
          • 1970-01-01
          • 2023-03-17
          相关资源
          最近更新 更多