sql多表關聯更新—用b表字段來更新a表對應的字段


在開發時,如果遇到表需要加字段,那么需要對存量數據刷新這個字段值

1、mysql

--兩張表關聯
UPDATE JC_COLL_REPAY r
INNER JOIN lc_lm_loan l ON r.loan_no = l.loan_no
SET r.loan_typ = l.tep_cde,
  r.oper_center = l.bch_cde,
  r.chnl_cde = l.coopr_cde;

--三張表關聯
UPDATE JC_COLL_REPAY r
INNER JOIN lc_lm_loan l ON r.loan_no = l.loan_no
INNER JOIN lc_cust_info i ON l.cust_id = i.cust_id
SET r.loan_typ = l.tep_cde,
  r.oper_center = l.bch_cde,
  r.chnl_cde = l.coopr_cde,
  r.indiv_mobile = i.indiv_mobile;

 

2、oracle

---三張表關聯
update JC_COLL_REPAY r
  set (r.indiv_mobile,r.loan_typ,r.oper_center,r.chnl_cde) =
  (select c.indiv_mobile,l.tep_cde,l.bch_cde,l.coopr_cde
    from lc_lm_loan l,lc_cust_info c
    where l.cust_id = c.cust_id and l.loan_no = r.loan_no
  )
  where exists (select 1
    from lc_lm_loan l,lc_cust_info c
    where l.cust_id = c.cust_id and l.loan_no = r.loan_no
  )


---不推薦
update JC_COLL_REPAY r 
set r.loan_typ=(select tep_cde from lc_lm_loan l where r.loan_no=l.loan_no),
  r.oper_center=(select bch_cde from lc_lm_loan l where r.loan_no=l.loan_no),
  r.chnl_cde=(select coopr_cde from lc_lm_loan l where r.loan_no=l.loan_no)
where exists (select 1 from a where r.loan_no=l.loan_no)

 

還可以使用merge into 

merge into TEST_RESULT r
     using (select * from test_major m,test_subject s where m.id = s.sb_ma) ms
     on (r.subject = ms.sb_name)
     when matched then 
     update set r.major = ms.zymc

 


免責聲明!

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



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