28
    UPDATE messages set test_read =1         WHERE userid='xyz'         ORDER BY date_added DESC          LIMIT 5, 5 ;

I am trying to use this query to update a set of 5 rows using limit but mysql is showing an error..The one below is working

    UPDATE messages set test_read =1         WHERE userid='xyz'         ORDER BY date_added DESC          LIMIT 5 ;

why is the first one not working?

Juan Mellado's user avatar
Juan Mellado
15.2k5 gold badges50 silver badges54 bronze badges
askedOct 3, 2009 at 8:39
halocursed's user avatar

2 Answers2

54

If you really must do it this way, you can use something like this:

 UPDATE messages SET test_read=1 WHERE id IN (     SELECT id FROM (         SELECT id FROM messages          ORDER BY date_added DESC           LIMIT 5, 5     ) tmp );
answeredOct 4, 2009 at 13:54
Lukáš Lalinský's user avatar
Sign up to request clarification or add additional context in comments.

5 Comments

Do you really need the double nested select? In ms sql it would just be something like "Where id in (SELECT TOP 5 id FROM messages ORDER BY date_added DESC)"
Yes, MySQL doesn't allow you do update a table that it selects from. The extra nested select forces it to save the results into a temporary table.
When you askif you really must do it this way, are you implying there is a better alternative to updating records based on a rank given by the order of one of its fields?
When I first looked at this answer, I thought surely this won't work, but it did! Great answer and thank you.
MySQL 5.5 does not support LIMIT in IN/ALL/ANY/SOME subquery.
5

http://bugs.mysql.com/bug.php?id=42415

The documentation states that any UPDATE statement with LIMIT clause is considered unsafe since the order of the rows affected is not defined:http://dev.mysql.com/doc/refman/5.1/en/replication-features-limit.html

However, if "ORDER BY PK" is used, the order of rows is defined and such a statement could be logged in statement format without any warning.

answeredApr 23, 2012 at 14:55
Svetoslav Genov's user avatar

Comments

Your Answer

Sign up orlog in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to ourterms of service and acknowledge you have read ourprivacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.