6

I have this SQL query, which is wrong. I want to update the field "prevmonth" in the wins table, but only for the record that has the maximum value for the field "month_wins".

UPDATE wins
SET prevmonth_top=1
WHERE month_wins = (SELECT MAX(month_wins) FROM wins)

Error message:

#1093 - You can't specify target table 'wins' for update in FROM clause

But how can I do this?

0

2 Answers 2

21

Try this trick:

UPDATE wins
SET prevmonth_top=1
ORDER BY month_wins DESC
LIMIT 1

Or something like this:

UPDATE IGNORE giveaways
SET winner = 1
WHERE month_wins = (select maxID from (SELECT MAX(ID) maxID FROM giveaways) as t)

It is the same as You can't specify target table 'table_name' for update in FROM clause.

1
  • 2
    FWIW: The first solution is nice and short, but be very careful not to omit "Limit 1" at the end! Jan 17, 2019 at 0:51
5

Run the following query. It may help:

UPDATE wins
SET prevmonth_top=1 WHERE month_wins =
(
    SELECT month_wins FROM (SELECT MAX(month_wins) FROM wins) AS month_wins
)
2
  • much more simple and clear! great dude! Feb 19, 2018 at 1:33
  • 1
    Minor nit: the use of month_wins in so many places makes this answer less clear than it could be. I'd change the nested selects to something like (SELECT maxWin FROM (SELECT MAX(month_wins) maxWin FROM wins) AS t). This clarifies that maxWin is the max value, not another reference to the field month_wins, and that t is an arbitrary temp name. Jan 17, 2019 at 0:57

Not the answer you're looking for? Browse other questions tagged or ask your own question.