SQL/Oracle 兩表關聯更新
阿新 • • 發佈:2019-01-08
有TA, TB兩表,假設均有三個欄位id, name, remark. 現在需要把TB表的name, remark兩個欄位通過id關聯,更新到TA表的對應欄位。
建表指令碼:
drop table TA; create table TA ( id number not null, name varchar(10) not null, remark varchar(10) not null ); drop table TB; create table TB ( id number not null, name varchar(10) not null, remark varchar(10) not null ); truncate table TA; insert into TA values(1, 'Aname1', 'Aremak1'); insert into TA values(2, 'Aname2', 'Aremak2'); commit; truncate table TB; insert into TB values(1, 'Bname1', 'Bremak1'); insert into TB values(3, 'Bname3', 'Bremak3'); commit; select * from TA; select * from TB;
SQLServer/Oracle版本的Update寫法分別如下:
1. SQLServer
update TA set name=b.name, remark=b.remark from TA a inner join TB b on a.id = b.id
或者
update TA set name=b.name, remark=b.remark from TA a, TB b where a.id = b.id
注意不要在被更新表的的欄位前面加別名字首,否則語法靜態檢查沒問題,實際執行會報錯。
Msg 4104, Level 16, State 1, Line 1
The multi-part identifier "a.name" could not be bound.
2. Oracle
update TA a set(name, remark)=(select b.name, b.remark from TB b where b.id=a.id)
where exists(select 1 from TB b where b.id=a.id)
注意如果不新增後面的exists語句,TA關聯不到的行name, remark欄位將被更新為NULL值, 如果name, remark欄位不允許為null,則報錯。 這不是我們希望看到的。
--when name, remark is not null, cause error. --if allow null, rows in TA not matched will be update to null. update TA a set(name, remark)=(select b.name, b.remark from TB b where b.id=a.id);
可考慮的替代方法:
update TA a set name= nvl((select b.name from TB b where b.id=a.id), a.name);
update TA a set remark= nvl((select b.remark from TB b where b.id=a.id), a.remark);
如果TA.id, TB.id是unique index或primary key
可以使用檢視更新的語法:
ALTER TABLE TA ADD CONSTRAINT TA_PK
PRIMARY KEY (
ID
)
ENABLE
VALIDATE
;
ALTER TABLE TB ADD CONSTRAINT TB_PK
PRIMARY KEY (
ID
)
ENABLE
VALIDATE
;
update (select a.name, b.name as newname,
a.remark, b.remark as newremark from TA a, TB b where a.id=b.id)
set name=newname, remark=newremark;
更加詳盡的對比分析參考下面的文章