代码之家  ›  专栏  ›  技术社区  ›  MoxGoat

如何防止update语句将某些记录设置为空?

  •  0
  • MoxGoat  · 技术社区  · 6 年前

    update t1 x
    set x.code =
    (select code from
    (select distinct address, city, prov, aflag, rcode from t2) y
    where x.address = y.address and x.city = y.city and x.state = y.state and x.flag = y.flag)
    where x.aflag like '%b%';
    

       t1               
    address city    state   flag    code
    123      aaa      il     b       400
    567      bbb      il     b       400
    345      bbb      il     b      -500
    789      ddd      il     b       600
    546      ccc      il     b       700
    

    表2:用于更新T1的代码列

    t2              
    address city    state   flag    code
       123   aaa      il      b     -555
       444   bbb      il      b     -555
       345   bbb      il      b     -555
       888   kkk      il      b     -555
       546   ccc      il      b     -555
    
    
    
    What the query currently outputs
    
         current output             
        address city    state   flag    code
           123   aaa      il      b     400
           444   bbb      il      b     NULL
           345   bbb      il      b     -500
           888   kkk      il      b     NULL
           546   ccc      il      b     -700
    

      What I want               
    address city    state   flag    code
      123    aaa      il      b     400
      444    bbb      il      b    -555
      345    bbb      il      b    -500
      888    kkk      il      b    -555
      546    ccc      il      b    -700
    

    3 回复  |  直到 6 年前
        1
  •  1
  •   Gordon Linoff    6 年前

    exists where

    update t1 x
        set x.code = (select code
                      from t2 y
                      where x.address = y.address and x.city = y.city and x.state = y.state and x.flag = y.flag and rownum = 1
                     )
        where x.aflag like '%b%' and
              exists (select code
                      from t2 y
                      where x.address = y.address and x.city = y.city and x.state = y.state and x.flag = y.flag and rownum = 1
                     );
    
        2
  •  1
  •   Thorsten Kettner    6 年前

    t2 都应告诉您要更新的行和使用的值。为此,请编写一个updatetable查询:

    update
    (
      select t1.code, t2.code as new_code
      from t1
      join t2 on  t2.address = t1.address
              and t2.city    = t1.city city 
              and t2.state   = t1.state
              and t2.flag    = t1.flag
      where t1.flag like '%b%'
    )
    set code = new_code;
    

    address, city, state, flag

        3
  •  0
  •   wolφi    6 年前

    有些人喜欢它,有些人不喜欢。它看起来与您最初的更新声明惊人地相似:

    MERGE INTO t1 x
    USING (SELECT DISTINCT address, city, state, flag, code from t2) y
       ON (x.address = y.address AND x.city = y.city AND x.state = y.state AND x.flag = y.flag)
     WHEN MATCHED THEN 
          UPDATE SET x.code = y.code
           WHERE x.flag LIKE '%b%';