Home > Database > Mysql Tutorial > Why Doesn't MySQL's `UPDATE` Statement Support a Two-Part `LIMIT` Clause?

Why Doesn't MySQL's `UPDATE` Statement Support a Two-Part `LIMIT` Clause?

Susan Sarandon
Release: 2024-12-31 21:19:19
Original
290 people have browsed it

Why Doesn't MySQL's `UPDATE` Statement Support a Two-Part `LIMIT` Clause?

MySQL: Difficulties with LIMIT in Multi-Row Updates

In MySQL, attempting to update multiple rows using the LIMIT clause can encounter errors. Consider the following query:

UPDATE messages SET test_read=1
WHERE userid='xyz'
ORDER BY date_added DESC
LIMIT 5, 5;
Copy after login

This query aims to update five rows based on the condition provided, skipping the first five rows (LIMIT 5, 5). However, this results in an error.

The working version of the query without the second LIMIT clause (LIMIT 5) successfully updates the first five rows meeting the condition. The error occurs because MySQL does not allow specifying a second LIMIT within an update statement.

Recommended Alternative

To overcome this limitation, a workaround is recommended:

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
);
Copy after login

This query achieves the same result by first identifying the desired rows using a subquery and then updating the appropriate rows based on the id field. This method allows for precise row selection and updating in MySQL.

The above is the detailed content of Why Doesn't MySQL's `UPDATE` Statement Support a Two-Part `LIMIT` Clause?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template