普通的 update
都是根據條件來對部分列的內容進行修改,用法如下:
update temp_cwh_table set name = 'xxx'
where id = 1;
假設現在有2張表:A、B,需要關聯A、B表,根據相同的 id
來 update
A表。
建立測試表
-- 創建測試表 temp_cwh_001
create table temp_cwh_001
(
id int,
name varchar2(20)
);
-- 插入數據
insert into temp_cwh_001 values (1,'AA');
insert into temp_cwh_001 values (2,'BB');
insert into temp_cwh_001 values (3,'CC');
-- 查詢
select * from temp_cwh_001
-- 1 1 AA
-- 2 2 BB
-- 3 3 CC
-- 創建測試表 temp_cwh_002
create table temp_cwh_002
(
id int,
name varchar2(20)
);
-- 插入數據
insert into temp_cwh_002 values (1,'CCCC');
insert into temp_cwh_002 values (2,'DDDD');
-- 查詢
select * from temp_cwh_002
-- 1 1 CCCC
-- 2 2 DDDD
關聯更新
-- 關聯更新
update temp_cwh_001 a
set name = (select b.name from temp_cwh_002 b where a.id = b.id);
-- 提交
commit;
-- 查詢
select * from temp_cwh_001;
-- 1 1 CCCC
-- 2 2 DDDD
-- 3 3
本意只是將關聯得上的內容進行update,關聯不上的內容不修改。但此用法下,關聯不上的內容直接被update為null,需再度優化。
- 方法一
-- 關聯更新
update temp_cwh_001 a
set name = (select b.name from temp_cwh_002 b where a.id = b.id)
where id = (select b.id from temp_cwh_002 b where a.id = b.id)
-- 提交
commit;
-- 查詢
select * from temp_cwh_001;
-- 1 1 CCCC
-- 2 2 DDDD
-- 3 3 CC
添加where條件過濾,符合條件。
- 方法二:使用exists
-- 關聯更新
update temp_cwh_001 a
set name = (select b.name from temp_cwh_002 b where a.id = b.id)
where exists (select 1 from temp_cwh_002 b where a.id = b.id)
-- 提交
commit;
-- 查詢
select * from temp_cwh_001;
-- 1 1 CCCC
-- 2 2 DDDD
-- 3 3 CC
- 方法三
update (select a.name aname,
a.id aid,
b.name bname,
b.id bid
from temp_cwh_001 a,
temp_cwh_002 b
where a.id = b.id)
set aname = bname
報錯: ORA-01779: cannot modify a column which maps to a non key-preserved table
需要主鍵的支持
alter table temp_cwh_001 add primary key(id);
alter table temp_cwh_002 add primary key(id);
重新執行,便可。
這種方法的局限性就是需要primary的支持。
- 方法四
可以使用存儲過程的方式進行靈活處理,不過這里有點復雜。。暫且記錄。。
declare
cursor cur_wm is select name, id from temp_cwh_002;
begin
for my_wm in cur_wm loop
update temp_cwh_001 set name = my_wm.name
where id = my_wm.id;
end loop;
end;
執行之后,PL/SQL procedure successfully completed.