oracle update with,Update query with Joins

本文介绍了在Oracle中更新JOIN操作中使用的表时的一个限制,即源表必须对目标表的每一行都是唯一的。通过一个例子展示了如何使用子查询更新目标表,并展示了更新操作后的结果,强调了子查询在保持数据唯一性中的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Oracle has the ability to update a table used in a join, however there is a restriction that Oracle must know in advance that the table acting as the source must be unique for each row in the target. (I hope I worded that correctly). You have the same restriction logically with a subquery because if it returns more than one row the update statement will fail. Here's an example:

create table source_table

(source_id number primary key

,s_col1 number

,s_col2 number

,s_col3 number

);

create table target_table

(target_id number primary key

,t_col1 number

,t_col2 number

,t_col3 number

);

insert into source_table(source_id,s_col1,s_col2,s_col3) values (101,111,1.01,-1);

insert into source_table(source_id,s_col1,s_col2,s_col3) values (102,222,2.02,-2);

insert into source_table(source_id,s_col1,s_col2,s_col3) values (103,333,3.03,-3);

insert into source_table(source_id,s_col1,s_col2,s_col3) values (104,444,4.04,-4);

insert into source_table(source_id,s_col1,s_col2,s_col3) values (105,555,5.05,-5);

insert into target_table(target_id,t_col1,t_col2,t_col3) values (101,null,null,null);

insert into target_table(target_id,t_col1,t_col2,t_col3) values (102,null,null,null);

insert into target_table(target_id,t_col1,t_col2,t_col3) values (103,null,null,null);

insert into target_table(target_id,t_col1,t_col2,t_col3) values (104,null,null,null);

insert into target_table(target_id,t_col1,t_col2,t_col3) values (105,null,null,null);

commit;

SQL> select * from target_table;

TARGET_ID T_COL1 T_COL2 T_COL3

-------------------- -------------------- -------------------- --------------------

101

102

103

104

105

update

(

select t_col1,t_col2,t_col3,s_col1,s_col2,s_col3

from target_table t

,source_table s

where t.target_id = s.source_id

)

set t_col1 = s_col1

,t_col2 = s_col2

,t_col3 = s_col3

;

5 rows updated.

SQL> select * from target_table;

TARGET_ID T_COL1 T_COL2 T_COL3

-------------------- -------------------- -------------------- --------------------

101 111 1.01 -1

102 222 2.02 -2

103 333 3.03 -3

104 444 4.04 -4

105 555 5.05 -5

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值