ORACLE多表關聯UPDATE 語句


1) 最簡單的形式

SQL 代碼

 --經確認customers表中所有customer_id小於1000均為'北京'

--1000以內的均是公司走向全國之前的本城市的老客戶:)
update customers
set city_name='北京'
where customer_id<1000

2) 兩表(多表)關聯update -- 僅在where字句中的連接

SQL 代碼
--這次提取的數據都是VIP,且包括新增的,所以順便更新客戶類別
update customers a -- 使用別名
set customer_type='01' --01 為vip,00為普通
where exists (select 1
from tmp_cust_city b
where b.customer_id=a.customer_id
)

3) 兩表(多表)關聯update -- 被修改值由另一個表運算而來

SQL 代碼
update customers a -- 使用別名
set city_name=(select b.city_name from tmp_cust_city b where b.customer_id=a.customer_id)
where exists (select 1
from tmp_cust_city b
where b.customer_id=a.customer_id
)
-- update 超過2個值
update customers a -- 使用別名
set (city_name,customer_type)=(select b.city_name,b.customer_type
from tmp_cust_city b
where b.customer_id=a.customer_id)
where exists (select 1
from tmp_cust_city b
where b.customer_id=a.customer_id
)


-- 方法1.
UPDATE  表2
SET
  表2.C  =  (SELECT  B  FROM  表1  WHERE   表1.A = 表2.A)
WHERE
  EXISTS ( SELECT 1 FROM   表1  WHERE   表1.A = 表2.A)
 
   
-- 方法2
MERGE INTO 表2 
USING 表1
ON ( 表2.A = 表1.A )    -- 條件是 A 相同
WHEN MATCHED THEN UPDATE SET 表2.C = 表1.B   -- 匹配的時候,更新
 
二,
oracle隨機讀取表中的N條數據方法:

1select * from (select * from tablename order by sys_guid()) where rownum < N; 
2select * from (select * from tablename order by dbms_random.value) where rownum< N; 
3select *  from (select * from table_name sample(10)   order by trunc(dbms_random.value(01000)))  where rownum < N;
 

說明:   sample(10)含義為檢索表中的10%數據,sample值應該在[0.000001,99.999999]之間,其中 sys_guid() 和 dbms_random.value都是內部函數
注:  在使1)方法時,即使用sys_guid() 這種方法時,有時會獲取到相同的記錄,即:和前一次查詢的結果集是一樣的(可能是和操作系統有關:windows正常,linux異常;也可能是因為sys_guid()函數本身的問題,有待繼續研究)  所以,為確保在不同的平台每次讀取的數據都是隨機的,建議采用2)和3)兩種方案,其中2)方案更常用。3)方案縮小了查詢的范圍,在查詢大表,且要提取數據不是很不多的情況下,會對查詢速度上有一定的提高

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM