update one line with the average of other line

时间:2016-04-25 09:19:14

标签: mysql sql


I actually have a table like this :
enter image description here
But I want to update the value of the first line to give it the value of the average of their child like this :
enter image description here
So I've used this query :

UPDATE mytable parent
INNER JOIN mytable child
ON child.parentId = parent.id
SET parent.value = AVG(child.value)
WHERE parent.parentId=0

But I get this error : #1111 - Invalid use of group function
How can I correct my query ?

2 个答案:

答案 0 :(得分:2)

Use a subquery to join on where you calculate the average for the parent id's

The query to get the average per parentId looks like:

SELECT parentId, AVG(value) as average FROM mytable GROUP BY parentId

So now join on it

UPDATE mytable parent
INNER JOIN (SELECT parentId, AVG(value) as average FROM mytable GROUP BY parentId) child
ON child.parentId = parent.id
SET parent.value = child.average
WHERE parent.parentId=0

答案 1 :(得分:2)

For single record update you could use variable:

SET @id = 0;--your ID
SET @avgVal = SELECT AVG(value) FROM mytable WHERE parentId = @id;

UPDATE mytable parent
   SET parent.value = @avgVal
WHERE parent.parentId = @id;