update關聯其他表批量更新資料

2022-03-31 09:39:37 字數 2278 閱讀 7945

批量更新表時,update乙個表的列時,需要依賴另外的表,這種依賴可以是where條件子句,也可以要update的field的值依賴另外的表

通常有兩種做法

1.使用儲存過程

2.在程式**裡逐條迴圈執行

這裡給出一種更高效、簡潔的做法,批量更新sql ,一句sql就可以替代麻煩的迴圈過程,有ms sqlserver、oracle、db2下的寫法

--關鍵點:t4和t1是同乙個table,primary key肯定也是同乙個,

--並以它進行關聯,這樣在 select語句裡即可引用到要update的表的fields 

update table1 as t1 

set (field1,field2) = (select field21, field22 

from table2 t2 

inner join table3 t3 

on t3.field31 = t2.field23 

inner join table4 t4 

on t3.field32 = t4.filed41 

where t2.field24 >= '' 

and t1.fid = t4.fid); 

----------------------------ms sqlserver --------------------------------------

update t1 

set field1 = field21, field2 = field22 

from table2 t2 

inner join table3 t3 

on t3.field31 = t2.field23 

inner join table4 t4 

on t3.field32 = t4.filed41 

where ((t2.field24 >= '') 

and t1.fid = t4.fid); 

----------------------------oracle --------------------------------------------

update table1 t1 

set (field1,field2) = (select field21, field22 

from table2 t2 

inner join table3 t3 

on t3.field31 = t2.field23 

inner join table4 t4 

on t3.field32 = t4.filed41 

where ((t2.field24 >= '') 

and t1.fid = t4.fid)) 

where exists (select field21, field22 

from table2 t2 

inner join table3 t3 

on t3.field31 = t2.field23 

inner join table4 t4 

on t3.field32 = t4.filed41 

where ((t2.field24 >= '') 

and t1.fid = t4.fid)); 

---------------------------------db2 ------------------------------------------

update table1 as t1 

set (field1,field2) = (select field21, field22 

from table2 t2 

inner join table3 t3 

on t3.field31 = t2.field23 

inner join table4 t4 

on t3.field32 = t4.filed41 

where ((t2.field24 >= '') 

and t1.fid = t4.fid)) 

where exists (select field21, field22 

from table2 t2 

inner join table3 t3 

on t3.field31 = t2.field23 

inner join table4 t4 

on t3.field32 = t4.filed41 

where ((t2.field24 >= '') 

and t1.fid = t4.fid));

-----**自

MySql批量更新語句(UPDATE)

下面建立乙個名為 bhl tes 的資料庫,並建立名為 test user 的表,字段分別為 id age name create database ifnot exists bhl test 檢視結果 檢視結果 張三 18 男 趙四 17 女 劉五 16 男 周七 19 女 檢視結果 張三 whe...

Oracle 大表之間關聯update

declare maxrows number default 5000 row id table dbms sql.urowid table p id table dbms sql.varchar2 table cursor acnt first cur is select use hash t1,...

資料庫學習 update(批量更新)

資料更新update命令 用指定要求的值更新指定表中滿足天劍的資料的指定列的值 語法形式 update 表名 set 列名 表示式 子查詢 列名 表示式 子查詢 where 條件表示式 示例 1 將所有教師工資上調 10 原表資料 執行兩次後結果 2 將所有計算機學院的老師工資上調 10 updat...