Oracle 兩表關聯更新三種方式

2021-09-29 10:00:22 字數 1918 閱讀 2897

參照t2表,修改t1表,修改條件為兩表的fname列內容一致,我們發現兩張表fname相同的只有a;

常見陷阱:

update t1 

set t1.fmoney = (select t2.fmoney from t2 where t2.fname = t1.fname)

執行後t1結果如下:

我們在更新t1表中a對應的值得時候,誤修改了b對應的值;

正確寫法:

我們在執行上述sql,會發生如下報錯,具體原因參加如下博文:

ora-01779: 無法修改與非鍵值儲存表對應的列

根據上述文章,我們發現是表缺少主鍵導致的問題,我們給t2表增加主鍵約束

alter table t2 add constraint t2_key primary key (fname)
重新測試,發現正常;

merge into t1

using (select t2.fname,t2.fmoney from t2) t

on (t.fname = t1.fname)

when matched then

update set t1.fmoney = t.fmoney;

m t2) t

on (t.fname = t1.fname)

when matched then

update set t1.fmoney = t.fmoney;

參考文章

[1].oracle 兩表關聯更新三種方式[n] 古道子

oracle關聯表更新

如果有a表和b表,sql server中用 update a set field2 b.filed2 from a,b where a.field1 b.field1搞定,所以用慣了sql server的更新表語句,再用oracle的那真是特別的拗口。情景一 如果只是更新固定值,oracle和sql...

ORACLE 關聯兩張表批量更新資料,實用方法

case 表一 新增字段 age,需要從 表二中 將age資料同步到表一中,或者 單純同步兩張表中的資料 表1 employee 被更新的表 字段 age 表2 t user 資料 表 只更新表1中 age 為null的資料 update employee e set age select u.ag...

oracle兩表關聯更新方法

建立兩張測試表 create table table1 id varchar2 10 val varchar2 20 create table table2 id varchar2 10 val varchar2 20 分別給兩張測試表插入測試資料 insert into table1 values...