[英]SQL db2 update query for multiple rows
我通过以下查询更新记录:
update tableA set Quantity=
(select count(*) from table B where ID=x)
where ID=x
update tableA set Quantity=
(select sum(Stock) from table C where ID=y)
where ID=y
实施例(更正):
来自tableA的所有ID分为2个表:TableB和TableC。 我必须使用TableB的计数更新TableA的数量字段(如果ID.TableA在TableB中),并使用TableC的sun(库存)更新TableA的数量字段(如果ID.TableA在TableC中)
像这样,有50万个ID需要更新。 我想知道如何在不执行500k查询的情况下完成此操作。
编辑:我正在从TableB获取行数,计数不是TableB的列。
任何帮助将不胜感激,TIA!
您可以使用相关子查询:
update tableA
set Quantity = (select count(*) from table B where B.ID = A.ID)
对于您的问题,您的表和列的名称对我来说不是100%清楚的,所以我猜测它们的有关信息。 必要时更正:
update tablea a set quantity = case
when (select count(*) from tableb where b.id = a.id) is not null then
(select count(*) from tableb b where b.id = a.id)
else
(select sum(stock) from tablec c where c.id = a.id)
end
declare global temporary table tablea(id int not null, quantity int) with replace on commit preserve rows not logged;
declare global temporary table tableb(id int not null) with replace on commit preserve rows not logged;
declare global temporary table tablec(id int not null, stock int) with replace on commit preserve rows not logged;
insert into session.tablea values (1, 0), (2, 0), (3, 0), (4, 0), (5, 0), (6, 0);
insert into session.tableb values 1, 1, 1, 2, 2, 3;
insert into session.tablec values (4, 3), (5, 2), (5, 2), (5, 1), (6, 3), (6, 4);
update session.tableA a
set Quantity=coalesce(
nullif((select count(*) from session.tableb b where b.ID=a.ID), 0)
, (select sum(stock) from session.tablec c where c.ID=a.ID)
);
select * from session.tableA;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.