简体   繁体   English

MySQL从另一个选择select sum()更新一个表

[英]mysql update one table with select sum() from another

I have the following query, which works: 我有以下查询,它可以工作:

select filename, hour, sum(joe) as joe_total, sum(bob) as bob_total
from t1
group by filename, hour

This gives thousands of rows of data under the following columns: 这在以下几列下提供了数千行数据:

filename, hour, joe_total, bob_total

Each filename contains 24 hours, so the first row of results would be 每个文件名包含24小时,因此结果的第一行是

filename1, 1, [joe_total_value_hour1], [bob_total_value_hour1]

... and the second row would be ...第二行是

filename1, 2, [joe_total_value_hour2], [bob_total_value_hour2]

... etc. ...等

I have another table called t2 with the following fields: 我还有一个名为t2的表,其中包含以下字段:

filename, hour, joe_total, bob_total, mary_total, gertrude_total

The table t2 also has thousands of rows (more than the result of the select above), but currently the columns joe_total and bob_total contain only zeros and need to be updated. 表t2还具有数千行(比上面的选择结果还要多),但是当前列joe_total和bob_total仅包含零,需要更新。

So I want to update t2 so that 所以我想更新t2

t2.joe_total = [resuls from the select].joe_total

and similarly for t2.bob_total for each filename/hour. 同样,每个文件名/小时的t2.bob_total也是如此。

Any ideas how I could accomplish this? 有什么想法我可以做到这一点吗?

Okay, so here's the query that worked: 好的,这是有效的查询:

update t2 t2u
inner join
(SELECT filename, HOUR , SUM( joe) ) AS joe_total, SUM( bob ) AS bob_total FROM t1 GROUP BY filename, HOUR) t
on (t2u.filename =t.filename and t2u.hour = t.hour)
SET      t2u.joe_total = t.joe_total,
    t2u.bob_total = t.bob_total,
    ...

Many thanks to Jon C for helping to break my mental icejam. 非常感谢Jon C帮助打破了我的精神僵局。

You can try something like this: 您可以尝试如下操作:

UPDATE t2 SET 
    t2.joe_total = t.joe_total,
    t2.bob_total = t.bob_total,
    ...
    FROM  
    (  
        select filename, hour, sum(joe) as joe_total, sum(bob) as bob_total
        from t1
        group by filename, hour 
    ) t  
WHERE t2.filename = t.filename
AND t2.hour = t.hour

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM