请教大家一个Oracle子查询更新表的问题:无法修改与非键值保存表对应的列

zhangmj10 2018-03-11 09:57:37
我在使用Oracle子查询更新表时报错:无法修改与非键值保存表对应的列,报错截图如下:


两个表,如下图:


建表语句如下:
create table test1(id1 int,id2 int,col1 int,col2 int);
create table test2(id1 int,id2 int,v1 int,v2 int);


初始化数据:
insert into test1(id1,id2,col1,col2)values(11,12,1001,1002);
insert into test1(id1,id2,col1,col2)values(13,14,1003,1004);
insert into test1(id1,id2,col1,col2)values(15,16,1005,1006);

insert into test2(id1,id2,v1,v2) values(21,22,2001,2002);
insert into test2(id1,id2,v1,v2) values(23,24,2003,2004);
insert into test2(id1,id2,v1,v2) values(25,26,2005,2006);
insert into test2(id1,id2,v1,v2) values(27,28,2007,2008);

【要求】:使用子查询更新表test1,即,将表test1中的col1字段修改为test2中的v1值;更新条件是test1.id1=test2.id1 and test1.id2=test2.id2。

我的sql语句如下(执行报错,但是不知道原因):

update(
select t1.col1,tt.v1 from test1 t1,
( select id1,id2,max(v1)v1 from test2 t2
group by id1,id2
)tt where t1.id1=tt.id1 and t1.id2=tt.id2
)t set t.col1=t.v1;

报错截图如下:


请问这种条件如何使用Oracle中的“子查询更新表”这种语法呢?
希望哪位能帮忙解决一下,谢谢了!
...全文
850 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
用merge 然后用rowid 匹配更新
liu志坚 2018-03-12
  • 打赏
  • 举报
回复

oracle 12C 版本不会报错,能正常执行。
oracle 11.2版本 报错跟你的一样。
应该是12C以上才支持你这种写法了。

jdsnhan 2018-03-12
  • 打赏
  • 举报
回复
1、test2表加唯一性索引 2、oracle11之前的版本可以 update( select /*+ BYPASS_UJVC */ t1.col1 ........

17,082

社区成员

发帖
与我相关
我的任务
社区描述
Oracle开发相关技术讨论
社区管理员
  • 开发
  • Lucifer三思而后行
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧