工作中遇到的數據更新,學習記錄。 1、使用update進行數據更新 1)最簡單的更新 update tablea a set a.price=1.00 2)帶條件的數據更新 update tablea a set a.price = 2.00 where a.id='02' 3)兩張表關聯更新為固定 ...
工作中遇到的數據更新,學習記錄。
1、使用update進行數據更新
1)最簡單的更新
update tablea a set a.price=1.00
2)帶條件的數據更新
update tablea a set a.price = 2.00 where a.id='02'
3)兩張表關聯更新為固定值
update tablea a set a.price =3.00 where exits(select 1 from tableb b where a.id=b.id)
將a,b相同id的 a表的price 欄位更新為 3.00
4)關聯更新數據來源第二張表
update tablea a set a.price=(select price from tablec c ) where exits (select 1 from tablec c where a.id=c.id)
將a表price欄位 更新為 id和c表id相同的數據
5)關聯更新多個欄位
update tablea a set ( a.price,a.type)=(select c.price,c.type from tablec c ) where exits (select 1 from tablec c where a.id=c.id)
更新a表的price 和 type 欄位
6)使用視圖方式更新
update (select a.price old,c.price as new from tablea a ,tablec c where a.id=c.id) set old=new
以上為自己瞭解到的Update使用方式,需要註意 a.id 和c.id需要一一對應。即c表只有一條id 與a表id對應,否則會報錯
ORA-01427:"single-row subquery returns more than one row"
單行查詢返回多行結果。是不能進行更新的。
2、merge 更新使用
工作中要對一個欄位:次數 進行更新 表數據量在 13w+ 需要兩表關聯 也就是 兩個 13w+ 的表進行關聯。
在使用update進行更新的時候,效率問題大大降低。加上限制條件更新 100條數據還用了6-8S,所以 update並不適用。
查閱資料看到merge 更新,便學習記錄。
MERGE 在SQL Server、Oracle資料庫中可用,MySQL、PostgreSQL中不可用。可以同時進行更新和插入操作。執行效率要高於INSERT+UPDATE。
語法:
MERGE INTO [your table-name] [rename your table here]USING ( [ your query ] )[rename your query-sql and using just like a table]
ON ([conditional expression ] AND [...]...)
WHEN MATHED THEN [here you can execute some update sql or something else ]
WHEN NOT MATHED THEN [execute something else here ! ]
示例
merge into tablea a ----要更新或者操作的表
using tablec c ----源表 using (select * from tablec ) c
on a.id=c.id --匹配條件
when matched then set a.price=c.price --當匹配時進行更新操作
when not matched then --不匹配進行插入操作
insert values values(c.id,c.price)
using 後不僅可以使用 表 也可以是 視圖或者子查詢 using (select * from tablec ) c
not matched 可以沒有 就是當不匹配什麼也不做。
總結:
之前說的使用update更新100行數據都需要6-8S 使用merge 更新全部數據(13W+ 與13W+ 關聯)只用了10S左右。更新效率可見要比update高很多。
僅供學習使用。