as400 update语句 问题

1、************************************************我新建了两张物理表,tab_1,tab_2,其中它们的数据分别为tab_1------------------------------------bm   mc          value1     value201  &nbs...显示全部
1、************************************************
我新建了两张物理表,tab_1,tab_2,其中它们的数据分别为
tab_1
------------------------------------
bm   mc          value1     value2
01   01编码        0          0
02   02编码        0          0
03   03编码        0          0
------------------------------------
tab_2
------------------------------------
bm   mc          value1
01   01编码        100         
------------------------------------
2、************************************************
然后我使用update语句
update tab_1 a set value1 = (select value1 from tab_2 b where a.bm=b.bm);
3、************************************************
可是最后查询结果却是这样
select * from tab_1;
tab_1
------------------------------------
bm   mc          value1     value2
01   01编码        100         0
02   02编码         -          0
03   03编码         -          0
------------------------------------
为02,03编码的value1值变成空值了。
select * from tab_1 where value1 is null;
tab_1
------------------------------------
bm   mc          value1     value2
02   02编码         -          0
03   03编码         -          0
------------------------------------收起
参与10

查看其它 6 个回答Xiao Qing的回答

Xiao QingXiao Qing  系统工程师 , 浪潮商用机器有限公司

update tab_1 a set value1 = (select value1 from tab_2 b where a.bm=b.bm) 这条SQL语句不管它该不该更新所有记录,但实际上它更新了 TAB_1这张表中的每一条记录,更糟糕的是TAB_2表中的 bm 字段的内容即使没有出现在TAB_1表中,这条SQL语句也将会把 TAB_1相对应的 value1字段置为null,这是绝对不准许的,因此要进行更有选择性的更新以避免错误的发生。

有两种方法可以解决这个问题:

Method 1:
update twtlib.tab_1 a
set value1=(select value1 from twtlib.tab_2 b where a.bm=b.bm)
where bm in (select bm from twtlib.tab_2);

Method 2:
update twtlib.tab_1 a set value1 = (select value1 from twtlib.tab_2 b where a.bm=b.bm)
where exists (select 1 from twtlib.tab_2 b where a.bm=b.bm);

执行结果如下图所示:

然后查看tab_1的内容,没有被误改为null的记录了,符合要求。

仅供参考。

系统集成 · 2021-04-15
浏览1105

回答者

Xiao Qing
系统工程师浪潮商用机器有限公司
擅长领域: 服务器新核心系统存储

Xiao Qing 最近回答过的问题

回答状态

  • 发布时间:2021-04-15
  • 关注会员:2 人
  • 回答浏览:1105
  • X社区推广