tags:

views:

18

answers:

2

I have a table with several hundred rows. I want to take the top 20 based on the value of column num and replace num with a number.

What I tried to do (which didn't work) was:

UPDATE table
SET num = 95
WHERE id IN (SELECT id FROM table ORDER BY id DESC LIMIT 20)

Any suggestions?

A: 

Try a small change:

UPDATE table
SET num = 95
WHERE id IN (SELECT id FROM table ORDER BY num DESC LIMIT 20)

If you want to get the top 20 num's, you need to sort by num's.

Byron Sommardahl
Good catch. The problem lies in the subquery's use of LIMIT, however. I will try this in any case. Edit: It's still complaining about the use of LIMIT in the subquery.
tipu
Can you run the subquery on its own?
Byron Sommardahl
@Byron: Yes. The error is that my version of MySQL does not support LIMIT in the subquery
tipu
+2  A: 

There's no need for the subquery - you can use LIMIT in an UPDATE statement on MySQL:

  UPDATE table
     SET num = 95
ORDER BY id DESC
   LIMIT 20

It's unclear what you want to order by - I used id based on your subquery, but in case it needs to be by the num value:

  UPDATE table
     SET num = 95
ORDER BY num DESC
   LIMIT 20
OMG Ponies
You beat me to it by seconds. I think it should be sorted by `num` though.
Mike
@Mike: You had a whole 17 minutes! :p Added the sort by num alternative, I was basing off the subquery the OP posted.
OMG Ponies
I wasn't aware that limit and order by worked in updates, thanks.
tipu
@tipu: That's why I linked to the documentation for MySQL UPDATE statements.
OMG Ponies