多条子查询的更新

[复制链接]
查看11 | 回复9 | 2021-10-12 20:11:36 | 显示全部楼层 |阅读模式
A表:
ACC BILL
12.0
24.0
35.0
B表:
ACC BILL
11.0
24.0
36.0
现在要查出所有A表和B表ACC字段一样但是BILL不一样的记录,并将B表的BILL更新到A表的BILL中去,应该怎么写UPDATE,尽量不用存储过程

回复

使用道具 举报

千问 | 2021-10-12 20:11:36 | 显示全部楼层
UPDATE A SET BILL=(SELECT BILL FROM B,A WHEREB.ACC=A.ACC)这样会提示单行子查询返回多行
回复

使用道具 举报

千问 | 2021-10-12 20:11:36 | 显示全部楼层
merge into 啊
回复

使用道具 举报

千问 | 2021-10-12 20:11:36 | 显示全部楼层
update a set a.bill=(select b.bill from b where a.acc=b.acc and a.billb.bill)
where exists(select 1 from b where a.acc=b.acc and a.billb.bill);
回复

使用道具 举报

千问 | 2021-10-12 20:11:36 | 显示全部楼层
2009532140 发表于 2016-5-9 16:33
merge into 啊

具体怎么做啊,求赐教
回复

使用道具 举报

千问 | 2021-10-12 20:11:36 | 显示全部楼层
dingjun123 发表于 2016-5-9 16:38
update a set a.bill=(select b.bill from b where a.acc=b.acc and a.billb.bill)
where exists(select...

多行返回的都可以这样做吗 更新的记录是一条条对应的吗
回复

使用道具 举报

千问 | 2021-10-12 20:11:36 | 显示全部楼层
dingjun123 发表于 2016-5-9 16:38
update a set a.bill=(select b.bill from b where a.acc=b.acc and a.billb.bill)
where exists(select...

这样的效率貌似有点低,现在a、b表虽然有点大,但是符合条件的只有几十个,但是我更新了10来分钟还没结束
回复

使用道具 举报

千问 | 2021-10-12 20:11:36 | 显示全部楼层
t069064449 发表于 2016-5-9 17:01
这样的效率貌似有点低,现在a、b表虽然有点大,但是符合条件的只有几十个,但是我更新了10来分钟还没结束

那就改成merge啊
merge into a using b on (a.acc=b.acc)
when matched
then
update set a.bill=b.bill
where a.billb.bill;
回复

使用道具 举报

千问 | 2021-10-12 20:11:36 | 显示全部楼层
t069064449 发表于 2016-5-9 17:01
这样的效率貌似有点低,现在a、b表虽然有点大,但是符合条件的只有几十个,但是我更新了10来分钟还没结束

把执行计划贴出来?
回复

使用道具 举报

千问 | 2021-10-12 20:11:36 | 显示全部楼层
确实快很多
SQL> create table tablea as select level acc,'name'||level bill from dual connect by level create table tableb as select level acc,'name'||level bill from dual connect by level update tableb set bill='xxx' where mod(acc,1000)=0;
已更新1000行。
已用时间:00: 00: 01.54
SQL> commit;
提交完成。
已用时间:00: 00: 00.01
SQL> update tablea a set a.bill=(select b.bill from tableb b where a.acc=b.acc and a.billb.bill)
2 where exists(select 1 from tableb b where a.acc=b.acc and a.billb.bill);
已更新1000行。
已用时间:00: 01: 38.34
SQL> select count(*) from tablea where bill='xxx';
COUNT(*)
----------
1000
已用时间:00: 00: 00.09
SQL> rollback;
回退已完成。
已用时间:00: 00: 00.04
SQL> select count(*) from tablea where bill='xxx';
COUNT(*)
----------
0
已用时间:00: 00: 00.04
SQL> merge into tablea a using tableb b on (a.acc=b.acc)
2 when matched
3 then
4 update set a.bill=b.bill
5 where a.billb.bill;
1000 行已合并。
已用时间:00: 00: 00.99
SQL> select count(*) from tablea where bill='xxx';
COUNT(*)
----------
1000
已用时间:00: 00: 00.04
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行