MySQL相关子查询

时间:2008-10-21 19:16:24

标签: mysql sql inner-join

难以阐明这种相关的子查询。我有两张表虚构的表,foo和bar。 foo有两个字段foo_id和total_count。 bar有两个字段,秒和id。

我需要为每个单独的id聚合bar中的秒数,并更新foo中的total_count。 id是foo_id栏中的外键。

我尝试过类似的东西而没有太多运气:

UPDATE foo f1 set total_count = (SELECT SUM(seconds) from bar b1 INNER JOIN foo f2     WHERE b1.foo_id = f2.id) WHERE f1.foo_id = bar.id;

5 个答案:

答案 0 :(得分:1)

UPDATE foo f1
SET total_count = (SELECT SUM(seconds)
FROM bar b1 WHERE b1.id = f1.foo_id)

您应该可以访问子查询中的相应foo id,因此无需加入表格。

答案 1 :(得分:1)

在较大的数据集中,相关子查询可能非常耗费资源。加入包含适当聚合的派生表可以更有效:

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

答案 2 :(得分:0)

我希望我理解你的问题。

您有以下表格:

  • foo - 列:idtotal_count
  • bar - 列:foo_id(引用foo.id)和seconds

以下查询应该有效(更新表total_count中的所有foo行):

UPDATE foo AS f1
SET total_count = (
  SELECT SUM(seconds) 
  FROM bar INNER JOIN foo 
  WHERE foo_id = f1.id
);

我不确定您要使用上一个WHERE子句(WHERE f1.foo_id = bar.id;)尝试做什么。

答案 3 :(得分:0)

这确实为一致性问题打开了大门。您可以考虑创建一个视图而不是改变foo表:

CREATE VIEW foo AS
SELECT id, sum(seconds) from bar group by id;

答案 4 :(得分:0)

为了提供替代方案,我喜欢使用MySQL的漂亮的多表更新功能:

UPDATE foo SET total_count = 0;

UPDATE foo JOIN bar ON (foo.foo_id = bar.id)
  SET foo.total_count = foo.total_count + bar.seconds;