Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL UPDATE and SELECT in one pass

Tags:

I have a MySQL table of tasks to perform, each row having parameters for a single task.
There are many worker apps (possibly on different machines), performing tasks in a loop.
The apps access the database using MySQL's native C APIs.

In order to own a task, an app does something like that:

  • Generate a globally-unique id (for simplicity, let's say it is a number)

  • UPDATE tasks
    SET guid = %d
    WHERE guid = 0 LIMIT 1

  • SELECT params
    FROM tasks
    WHERE guid = %d

  • If the last query returns a row, we own it and have the parameters to run

Is there a way to achieve the same effect (i.e. 'own' a row and get its parameters) in a single call to the server?

like image 668
Paul Oyster Avatar asked Feb 18 '09 20:02

Paul Oyster


People also ask

Can you use the UPDATE and select in one SQL statement?

The subquery defines an internal query that can be used inside a SELECT, INSERT, UPDATE and DELETE statement. It is a straightforward method to update the existing table data from other tables. The above query uses a SELECT statement in the SET clause of the UPDATE statement.

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.


1 Answers

try like this

UPDATE `lastid` SET `idnum` =  (SELECT `id` FROM `history` ORDER BY `id` DESC LIMIT 1);

above code worked for me

like image 175
charles Avatar answered Sep 23 '22 22:09

charles