• Oracle根据B表查询的结果更新A表的一个或多个列


    一、根据查询到的结果更新一列数据

    update A set A.name = (select B.name from B where A.id_no = B.id); -- A表的 id_no和B表的 id作为A表和B表的关联,确保A表中对应的 id_no只有一个name值需要更新

    (小提示:Sql Server中是通过update...from...来做到类似的操作,MySQL也有自己的方式实现,但是Oracle并不通用)

    二、根据查询到的结果更新多列数据

    1、通过相关子查询

    update A set (A.name , A.score) = (select B.name , B.score from B where A.id_no = B.id); -- 这里的理解和更新一列数据的SQL是相同的。

    -- 按照更新一列的逻辑和Oracle常用的多个数据更新习惯,应该是有几个属性需要更新就有几个对应的子查询,例如:

    update A set A.name = (select B.name from B where A.id_no = B.id) ,A.score= (select B.score from B where A.id_no = B.id);  -- 上面的SQL相当于对同一张表获取的数据做了一个简写

    2、通过内联视图

    update ( select A.id_no Aid_no , A.name Aname, A.score Ascore, B.id Bid, B.name Bname, B.score Bscore from A inner join B on (A.id_no = B.id) ) set Aname = Bname, Ascore = Bscore;

    (注:这种方式也适合更新单列的数据。这里就是把需要更新的数据和用于更新的数据放到同一个视图中然后对这个视图根据视图自己的数据来进行更新。)

    3、通过Merge into来实现更新

    Merge into的用法就是向一张表里插入数据的时候进行判断,如果表里没有则新增;如果存在则修改,所以这里可以利用来做批量的修改。(最后两个链接转载对merge into的介绍)

    merge into A using B  on A.id_no = B.id when matched then update set A.name = B.name when not matched then insert (A.id_no, A.name, A.score) values (B.id, B.name, B.score);

    (这里最好是确认B表的数据是A表都有的或者B表就是查询出的对应的数据;还有就是对插入新数据的部分when not matched then做处理,这里要看版本。)

    注意:以上的update脚本都没有加where条件,会更新对应列的所有数据,有关联的会更新成对应的数据,没有关联的会更新为NULL。

    参考信息:

    https://www.linuxidc.com/Linux/2014-06/103552.htm

    https://bbs.csdn.net/topics/340196496

    https://blog.csdn.net/spw55381155/article/details/79891305

    https://blog.csdn.net/jackpk/article/details/50336941

    https://www.cnblogs.com/flyingorchid/p/13411834.html

  • 相关阅读:
    洛谷
    洛谷
    洛谷
    模板
    洛谷
    洛谷
    Codeforces Round #561 (Div. 2) E. The LCMs Must be Large(数学)
    Codeforces Round #561 (Div. 2)
    Mail.Ru Cup 2018 Round 2 C. Lucky Days(拓展欧几里得)
    The 10th Shandong Provincial Collegiate Programming Contest H.Tokens on the Segments(贪心+优先级队列 or 贪心+暴力)
  • 原文地址:https://www.cnblogs.com/crrc/p/15103528.html
Copyright © 2020-2023  润新知