如何使用加入和分组进行更新?

时间:2016-07-29 14:55:23

标签: mysql

我想做这样的查询:

UPDATE State
LEFT JOIN Actions ON Actions.id = State.id
SET duration = FLOOR(AVG(duration)) WHERE type = 'started' GROUP BY Actions.id

我该怎么做? (它表示分组是错误的)

2 个答案:

答案 0 :(得分:2)

UPDATE State
INNER JOIN 
(
   select id, FLOOR(AVG(duration)) as avg
   from Actions
   WHERE type = 'started'
   group by id        
) tmp ON tmp.id = State.id
SET duration = tmp.avg

答案 1 :(得分:0)

简短回答是:

UPDATE状态LEFT JOIN操作ON Actions.id = State.id SET duration = FLOOR(AVG(duration))WHERE Actions.id IN(从Actions中选择id,其中Actions.id = state.id和type ='started'GROUP BY Actions.id)

可能在语法上不太正确。