"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Update Rows and Get Updated IDs in MySQL Without a Subquery?

How to Update Rows and Get Updated IDs in MySQL Without a Subquery?

Published on 2024-11-08
Browse:881

How to Update Rows and Get Updated IDs in MySQL Without a Subquery?

Combining SELECT and UPDATE Queries in MySQL

Combining SELECT and UPDATE queries into a single operation can be useful for optimizing database performance. In this case, a user wishes to combine the following queries:

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

While a subquery approach may not provide the desired results, there is a solution that can achieve the goal without a subquery. This solution involves using a user-defined variable (@uids) to store the updated row IDs:

UPDATE footable
   SET foo = 'bar'
 WHERE fooid > 5
   AND ( SELECT @uids := CONCAT_WS(',', fooid, @uids) );
SELECT @uids;```
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3