Oracle 多表關聯update
阿新 • • 發佈:2019-02-09
多表關聯執行update
1.僅在where子句中連線
--table2中全部為優秀學生,將table1中的優秀學生的成績更新為優
update table1 t1 set t1.grade = '優'
where exists (
select 1 from table2 t2 where t2.id = t1.id
);
2.update的值來自另一個表
看完以下例子,你就會明白了。
示例:表t_tst_bkin儲存了銀行聯行行號及其上級機構的聯行行號,現在需要將每個銀行的總部的聯行行號維護進sup_lbnk_no欄位
初始化sql:
--建立表 create table t_tst_bkin ( lbnk_no varchar2(12) not null enable, lbnk_nm varchar2(256) not null enable, up_lbnk_no varchar2(12) not null enable, sup_lbnk_no varchar2(12), primary key (lbnk_no) ); comment on table t_tst_bkin is '聯行行號資訊表'; comment on column t_tst_bkin.lbnk_no is '支付行號'; comment on column t_tst_bkin.lbnk_nm is '機構名稱'; comment on column t_tst_bkin.up_lbnk_no is '上級機構支付行號'; comment on column t_tst_bkin.sup_lbnk_no is '總部支付行號';
--初始化資料 insert into T_TST_BKIN(LBNK_NO,LBNK_NM,UP_LBNK_NO,SUP_LBNK_NO) values('104227600050','中國銀行葫蘆島化工街支行','104222017850',''); insert into T_TST_BKIN(LBNK_NO,LBNK_NM,UP_LBNK_NO,SUP_LBNK_NO) values('104227600068','中國銀行葫蘆島龍港支行','104222017850',''); insert into T_TST_BKIN(LBNK_NO,LBNK_NM,UP_LBNK_NO,SUP_LBNK_NO) values('104222017850','中國銀行大連市分行','104100000004',''); insert into T_TST_BKIN(LBNK_NO,LBNK_NM,UP_LBNK_NO,SUP_LBNK_NO) values('104100000004','中國銀行總行','104100000004','');
步驟一:
--維護總部的sup_lbnk_no欄位,條件為lbnk_no=up_lbnk_no
update t_tst_bkin t set t.sup_lbnk_no = lbnk_no where t.lbnk_no = t.up_lbnk_no;
步驟二(此處用到了兩表關聯update,且update的資料來自另一個表):
--將上級機構的sup_lbnk_no維護進該機構sup_lbnk_no update t_tst_bkin t set t.sup_lbnk_no = (select tt.sup_lbnk_no from t_tst_bkin tt where tt.sup_lbnk_no is not null and t.up_lbnk_no = tt.lbnk_no) where exists (select 1 from t_tst_bkin tt where tt.sup_lbnk_no is not null and t.up_lbnk_no = tt.lbnk_no) and t.sup_lbnk_no is null;
若存在多級機構,執行完步驟一,然後重複執行步驟二即可。
或許該例子存在其他便捷的實現該功能的sql,此處僅作為示例。