我正在通过以下查询更新记录:
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中),并用sunC(股票)更新TableC的数量字段(如果ID.TableA在TableC中)
有50万个ID需要更新。我想知道如何在不执行500k查询的情况下完成此操作。
编辑:我正在从TableB中获取行数,count不是TableB的列。
TIA会提供任何帮助!
答案 0 :(得分:0)
您可以使用相关子查询:
inline
答案 1 :(得分:0)
从您的问题中,您对表和列的名称并不是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
答案 2 :(得分:0)
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;