MySQL UPDATE 和 SELECT 一次完成

2021-11-20 00:00:00 sql-update mysql

我有一个要执行的 MySQL 任务表,每一行都有一个任务的参数.
有许多工作应用程序(可能在不同的机器上),循环执行任务.
应用程序使用 MySQL 的原生 C API 访问数据库.

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:

  • 生成一个全局唯一的 id(为简单起见,假设它是一个数字)

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

更新任务
SET guid = %d
WHERE guid = 0 LIMIT 1

选择参数
来自任务
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?

推荐答案

试试这个

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

以上代码对我有用

相关文章