关于SQL 多表关联update 解决示例

(一)问题产生

  1 问题是客户要求数据库中的一个字段需要进行批量的更新(从一张表里拿一个字段的多个值,赋值给另一张表的一个字段的多个值中)  --- 也不知道自己说明白没!!

   自己以前没有写过这样的SQL ,于是在网上搜索了一下。找到了方法,写了相关的SQL成功的解决了客户的问题。很开心!!

(二)解决方案 

  1 多表关联update单字段
    update stu t set t.NAME = (select t1.NAME from stu1 t1 where t1.ID = t.ID)
    where exists(select 1 from stu1 t2 where t2.ID = t.ID);

  写给客户的SQL 如下 

update hi_psnjob t 
set t.jobglbdef5 = (
        select t1.glbdef2
        from om_post t1
        where t1.pk_post = t.pk_post and t.lastflag = 'Y'
)
where exists(select 1 from om_post t2 where t2.pk_post = t.pk_post and t.lastflag = 'Y')

  2多表关联update多字段
    update stu t set (t.NAME, t.SEX) = (select t1.NAME, t1.SEX from stu1 t1 where t1.ID = t.ID)
    where exists(select 1 from stu1 t2 where t2.ID = t.ID);


    知识很多,需要学习的地方还有很多。

              慢慢来吧。