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)方案缩小了查询的范围,在查询大表,且要提取数据不是很不多的情况下,会对查询速度上有一定的提高

猜你喜欢

转载自www.cnblogs.com/jijm123/p/12979835.html