MySQL相关子查询
很难表达这个相关的子查询。我有两张桌子虚拟的桌子,foo和bar。foo有两个字段foo_id和total_count。条形图有两个字段,秒和id 我需要将每个id的秒数聚合到条形图中,并更新foo中的总计数。id是foo_id的外键 我也尝试过类似的方法,但运气不太好:MySQL相关子查询,mysql,sql,inner-join,Mysql,Sql,Inner Join,很难表达这个相关的子查询。我有两张桌子虚拟的桌子,foo和bar。foo有两个字段foo_id和total_count。条形图有两个字段,秒和id 我需要将每个id的秒数聚合到条形图中,并更新foo中的总计数。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) W
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;
我希望我正确理解了你的问题 您有以下表格:
- 表
-列:foo
和id
total\u count
- 表
-列:bar
(参考foo\u id
)和foo.id
seconds
foo
中的所有total\u count
行):
我不确定您对上一个WHERE
子句(WHERE f1.foo\u id=bar.id;
)试图做什么
您应该可以访问子查询中适当的foo id,因此不需要加入表。这确实打开了一致性问题的大门。您可以考虑创建视图,而不改变Foo表:
CREATE VIEW foo AS
SELECT id, sum(seconds) from bar group by id;
为了提供另一种选择,我喜欢使用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;
在较大的数据集中,相关子查询可能会占用大量资源。连接到包含适当聚合的派生表可能更有效:
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
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;
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