關於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);

 

 


 

 

 

    知識很多,需要學習的地方還有很多。

              慢慢來吧。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM