如何使用group更新选择查询?

时间:2013-08-01 08:39:16

标签: mysql sql

如何使用正确total_talktime的以下查询的SUM更新mobile_users表上的行user_id?使用group by?

这是选择查询:

SELECT SUM( TIME_TO_SEC( TIMEDIFF( `calls`.`finished_call` , `calls`.`start_call` ) ) ) AS `t` , `mobile_users`.`id`
FROM `mobile_users` 
LEFT JOIN `calls` ON `calls`.`user_id` = `mobile_users`.`id`
GROUP BY `mobile_users`.`id` 

我怎样才能使用Update Select,包括分组?

3 个答案:

答案 0 :(得分:1)

我认为您的查询正在运行 试试这个

update table   
set total_talktime = (select t from  
(SELECT SUM (TIME_TO_SEC (TIMEDIFF ( `calls`.`finished_call` , `calls`.`start_call`  ) ) ) AS `t`, `mobile_users`.`id`
FROM `mobile_users` 
LEFT JOIN `calls` ON `calls`.`user_id` = `musers`.`id`
GROUP BY `mobile_users`.`id` ) as subquery)

答案 1 :(得分:0)

尝试:

UPDATE mobile_users SET total_talktime = (SELECT SUM( TIME_TO_SEC( TIMEDIFF( calls.finished_call , calls.start_call ) ) ) AS t , mobile_users.id FROM mobile_users LEFT JOIN calls ON calls.user_id = musers.id GROUP BY mobile_users.id )

答案 2 :(得分:0)

我没有测试过该查询,但希望这会有所帮助:

update table
set total_talktime  = derived.t
from table, 
(
SELECT SUM( TIME_TO_SEC( TIMEDIFF( `calls`.`finished_call` , `calls`.`start_call` ) ) ) AS `t` , `mobile_users`.`id`
FROM `mobile_users` 
LEFT JOIN `calls` ON `calls`.`user_id` = `mobile_users`.`id`
GROUP BY `mobile_users`.`id` 
) derived
where table.userId = derived.id