I actually have a table like this :
But I want to update the value of the first line to give it the value of the average of their child like this :
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 ?
答案 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;