赞
踩
create table t1 (
FNAME varchar2(10),
FMONEY varchar2(10)
);
select * from t1 ;
create table t2 (
FNAME varchar2(10),
FMONEY varchar2(10)
);
select * from t2;
参照T2表,修改T1表,修改条件为两表的fname列内容一致,我们发现两张表fname相同的只有A;
常见陷阱:
UPDATE T1
SET T1.FMONEY = (select T2.FMONEY from t2 where T2.FNAME = T1.FNAME)
执行后T1结果如下:
我们在更新t1表中A对应的值得时候,误修改了B对应的值;
正确写法:
UPDATE T1
SET T1.FMONEY = (select T2.FMONEY from t2 where T2.FNAME = T1.FNAME)
WHERE EXISTS(SELECT 1 FROM T2 WHERE T2.FNAME = T1.FNAME);
UPDATE (
select t1.fmoney fmoney1,t2.fmoney fmoney2 from t1,t2 where t1.fname = t2.fname
)t
set fmoney1 =fmoney2;
我们在执行上述sql,会发生如下报错,具体原因参加如下博文:
根据上述文章,我们发现是表缺少主键导致的问题,我们给t2表增加主键约束
alter table T2 add constraint T2_KEY primary key (FNAME)
重新测试,发现正常;
merge into t1
using (select t2.fname,t2.fmoney from t2) t
on (t.fname = t1.fname)
when matched then
update set t1.fmoney = t.fmoney;
m t2) t
on (t.fname = t1.fname)
when matched then
update set t1.fmoney = t.fmoney;
参考文章
[1].ORACLE 两表关联更新三种方式[N] 古道子
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。