Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

update multiple rows using limit in mysql?

    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?

like image 755
halocursed Avatar asked Oct 03 '09 08:10

halocursed


People also ask

Can you UPDATE multiple rows in MySQL?

ON DUPLICATE KEY UPDATE clause and UPDATE with JOIN() function to update multiple columns in multiple rows with different values in MySQL.

Can we use limit in UPDATE query MySQL?

Yes, it is possible to use UPDATE query with LIMIT in MySQL.

Can we UPDATE multiple rows in a single UPDATE statement?

Column values on multiple rows can be updated in a single UPDATE statement if the condition specified in WHERE clause matches multiple rows. In this case, the SET clause will be applied to all the matched rows.


2 Answers

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  ); 
like image 135
Lukáš Lalinský Avatar answered Oct 13 '22 21:10

Lukáš Lalinský


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.

like image 26
Svetoslav Genov Avatar answered Oct 13 '22 20:10

Svetoslav Genov