-1

I might be overlooking something very obvious but I cannot get my multiple UPDATE statement to run. What I want to achieve is to SELECT an AVG() value from a table and UPDATE a column based on these values in another table.

I followed the following solution, but could not make it run:

Orginal answer

my solution:

UPDATE
  teams
SET
  teams.overall_rank = q.rank_avg
FROM
  (
    SELECT
      team_id as t_id,
      AVG(rank) as rank_avg
    FROM
      team_list
    WHERE
      rank NOT IN (0, -1)
    GROUP BY
      team_id
    ORDER BY
      rank_avg
  ) q
WHERE
  q.t_id = teams.team_id

The error message:

You have an error in your SQL syntax; it seems the error is around: 'FROM ( SELECT team_id as t_id, AVG(rank) as rank_avg FR' at line 5

I am using MySQL. What am I missing here?

JoeBe
  • 1,224
  • 3
  • 13
  • 28

2 Answers2

1

Try below - your syntax is not valid for mysql

UPDATE teams
join
  (
    SELECT
      team_id as t_id,AVG(rank) as rank_avg
      FROM team_list
      WHERE rank NOT IN (0, -1)
      GROUP BY team_id
   ) q on q.t_id = teams.team_id 
SET teams.overall_rank = q.rank_avg
Fahmi
  • 37,315
  • 5
  • 22
  • 31
1

I think you need a join:

UPDATE teams t INNER JOIN (
    SELECT
      team_id as t_id,
      AVG(rank) as rank_avg
    FROM team_list
    WHERE rank NOT IN (0, -1)
    GROUP BY team_id
) q ON q.t_id = t.team_id 
SET t.overall_rank = q.rank_avg

The ORDER BY in the subquery is not needed.

forpas
  • 160,666
  • 10
  • 38
  • 76