Home > Database > Mysql Tutorial > How to Update a Specific Number of Rows in MySQL Using LIMIT?

How to Update a Specific Number of Rows in MySQL Using LIMIT?

Mary-Kate Olsen
Release: 2025-01-02 14:36:44
Original
634 people have browsed it

How to Update a Specific Number of Rows in MySQL Using LIMIT?

Update Multiple Rows with LIMIT in MySQL

You are attempting to update a specific number of rows using a LIMIT clause in a MySQL query, but encountering an error. Let's understand why your initial query may have failed and how to fix it.

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

The above query is not valid because LIMIT expects a positive integer representing the offset from the beginning of the result set, and then the number of rows to be updated. In your query, you have specified both an offset (5) and a limit (5), which is incorrect.

To update a specific number of rows starting from an offset, you can use a subquery to select the rows to be updated and then update them. Here's a revised query:

UPDATE messages SET test_read=1
WHERE id IN (
    SELECT id FROM (
        SELECT id FROM messages 
        ORDER BY date_added DESC  
        LIMIT 5
    ) tmp
);
Copy after login

In this query, a subquery is used to select the IDs of the rows to be updated, starting from the 5th row in descending order of the date_added column. The main query then uses the IN clause to update only these specific rows.

The above is the detailed content of How to Update a Specific Number of Rows in MySQL Using LIMIT?. 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