在较大的数据集中,相关的子查询可能会占用大量资源。连接到包含适当聚合的派生表会更有效:
create table foo ( foo_id int identity, total_count int default 0 )
create table bar ( foo_id int, seconds int )
insert into foo default values
insert into foo default values
insert into foo default values
insert into bar values ( 1, 10 )
insert into bar values ( 1, 11 )
insert into bar values ( 1, 12 )
/* total for foo_id 1 = 33 */
insert into bar values ( 2, 10 )
insert into bar values ( 2, 11 )
/* total for foo_id 2 = 21 */
insert into bar values ( 3, 10 )
insert into bar values ( 3, 19 )
/* total for foo_id 3 = 29 */
select *
from foo
foo_id total_count
----------- -----------
1 0
2 0
3 0
update f
set total_count = sumsec
from foo f
inner join (
select foo_id
, sum(seconds) sumsec
from bar
group by foo_id
) a
on f.foo_id = a.foo_id
select *
from foo
foo_id total_count
----------- -----------
1 33
2 21
3 29