Home > Database > Mysql Tutorial > body text

## How to Retrieve and Update MySQL Rows in a Single Operation Without Subqueries?

Susan Sarandon
Release: 2024-10-25 02:26:30
Original
731 people have browsed it

## How to Retrieve and Update MySQL Rows in a Single Operation Without Subqueries?

Query to Retrieve and Update MySQL Rows in a Single Operation

Combining SELECT and UPDATE queries into a single operation can enhance efficiency and reduce code complexity. This article explores a solution to achieve this objective without using subqueries.

Conundrum

A user sought assistance in combining the following MySQL queries:

SELECT * FROM table WHERE group_id = 1013 and time > 100;
Copy after login
UPDATE table SET time = 0 WHERE group_id = 1013 and time > 100
Copy after login

The primary goal was to retrieve the desired rows while simultaneously updating their "time" field to zero.

Ingenious Solution

The solution involves using stored procedures to achieve the desired result. Stored procedures encapsulate a series of SQL statements and can be executed as a unit.

The following procedure named "update_and_retrieve" accomplishes the task:

<code class="mysql">CREATE PROCEDURE update_and_retrieve(IN group_id INT, IN time INT)
BEGIN
    DECLARE updated_ids VARCHAR(255);

    UPDATE table SET time = 0 WHERE group_id = group_id AND time > time;

    SET updated_ids = (SELECT GROUP_CONCAT(fooid) FROM table WHERE group_id = group_id AND time > time);

    SELECT * FROM table WHERE fooid IN (updated_ids);
END;</code>
Copy after login

Procedure Invocation

To invoke the stored procedure, simply execute the following statement:

<code class="mysql">CALL update_and_retrieve(1013, 100);</code>
Copy after login

This will update the "time" field to zero for the qualifying rows and then retrieve and display those updated rows.

Benefits

This approach offers several advantages:

  • Avoids unnecessary network round trips by combining multiple operations into a single call.
  • Simplifies code structure by eliminating the need for separate queries.
  • Enhances performance by reducing the database load.

The above is the detailed content of ## How to Retrieve and Update MySQL Rows in a Single Operation Without Subqueries?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!