Oracle 2张表关联更新

Oracle数据库中2张表T_1和表T_2,T_1信息需要根据T_2表信息进行批量变更,2张表根据ID进行关联。
1.创建2张表,没有设置主键create table T_1
(
  ID    NUMBER(2),
  YEAR  VARCHAR2(20),
  MONTH VARCHAR2(10) 
);
create table T_2
(
  ID    NUMBER(2),
  YEAR  VARCHAR2(20),
  MONTH VARCHAR2(10)
 
);
2.为T_1表、T_2表插入数据insert into T_1 (ID, YEAR, MONTH)values (1, '2011', '1');
insert into T_1 (ID, YEAR, MONTH)values (2, '2011', '2');
insert into T_1 (ID, YEAR, MONTH)values (3, '2011', '3');
commit;

insert into T_2 (ID, YEAR, MONTH)values (1, '2010', '11');
insert into T_2 (ID, YEAR, MONTH)values (2, '2010', '12');
commit;

3.删除表数据delete from T_1;
delete from t_2;
commit;

4.希望用t_2表的数据更新t_1表的数据,前提是2个表的id

方法一:

update t_1   a  set (a.year,a.month) =(select b.year,b.month from T_2 b where b.id=a.id);
commit;
执行结果结果:
1 2010 11
2 2010 12
3
执行结果会将t_1.id =3的year,month置为空,因为这个语句是对t_1表记录进行全量变更,如果在T_2表中不存在记录则会对T_1表记录置空;
处理方法:如果不想得到这样的结果,需要增加一个where条件。
update t_1   a  set (a.year,a.month) =(select b.year,b.month from T_2 b where b.id=a.id)
where a.id=(select c.id from year4 c where a.id=c.id); 
commit;
执行结果:
1 2010 11
2 2010 12
3 2011 3
方法二:where条件使用exists
update t_1   a  set (a.year,a.month) =(select b.year,b.month from T_2 b where b.id=a.id)
where exists (select 1 from T_2 b where b.id=a.id)
commit;
执行结果:
同方法一。
方法三:游标
declare  
  cursor target_cur is select year,month,id from t_2;  
  begin 
for my_cur in target_cur loop  
     update t_1 set year=my_cur.year,month=my_cur.month
   where id=my_cur.id; 
  end loop;  
end;
执行结果:
执行结果:同方法一。
方法四:
update (select a.year aYear,a.id aId,a.month aMonth,b.year bYear,b.id bId,b.month bMonth  from t_1 a,t_2 b where a.id = b.id) set aYear = bYear,aMonth = bMonth;
commit;
执行结果:
报oracle错误ora-01779,无法修改于非键值保存表对应列。

处理方法:将2个表的id设置为各自表的主键,然后再次执行后得到正确结果。
alter table T_1 add constraint t1_key_id primary key (ID);
alter table T_2 add constraint t2_key_id primary key (ID);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值