sql多表关联更新—用b表字段来更新a表对应的字段

文章介绍了在数据库开发中如何对已有数据的字段进行添加和更新值,提供了MySQL和Oracle两种数据库的SQL语句示例,包括两表关联和三表关联的更新方法,以及不推荐的子查询方式。还提及了使用MERGE语句进行数据匹配更新的可能性。
摘要由CSDN通过智能技术生成

在开发时,如果遇到表需要加字段,那么需要对存量数据刷新这个字段值
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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

恒二哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值