MySQL LAST_INSERT_ID 查询

MySQL LAST_INSERT_ID Query

我看过 official documentation 但我还是有点困惑。

假设我有一个过程,它运行并执行插入,然后我请求 LAST_INSERT_ID(),我是否从我的过程实例 运行 刚刚完成的插入中获取最后一个插入 ID或者它是任何 instance/session 在 table 上的最后一个插入 ID,它被称为过程?

例如,最后插入的记录 ID 为 4,我调用了该过程,我的插入 ID 为 5,但我的插入失败,我将返回 4 作为最后插入 ID 或 null/0 值?

您在问题中提供的文档页面非常 link 有答案:

The ID that was generated is maintained in the server on a per-connection basis. This means that the value returned by the function to a given client is the first AUTO_INCREMENT value generated for most recent statement affecting an AUTO_INCREMENT column by that client. This value cannot be affected by other clients, even if they generate AUTO_INCREMENT values of their own. This behavior ensures that each client can retrieve its own ID without concern for the activity of other clients, and without the need for locks or transactions.

因此,不存在来自其他客户端的竞争条件。您需要在与 INSERT 相同的连接中请求 LAST_INSERT_ID() 以获得正确的结果。

至于,事务回滚时会发生什么,未定义:

If the previous statement returned an error, the value of LAST_INSERT_ID() is undefined. For transactional tables, if the statement is rolled back due to an error, the value of LAST_INSERT_ID() is left undefined. For manual ROLLBACK, the value of LAST_INSERT_ID() is not restored to that before the transaction; it remains as it was at the point of the ROLLBACK.

您链接到的文档说:

The ID that was generated is maintained in the server on a per-connection basis. This means that the value returned by the function to a given client is the first AUTO_INCREMENT value generated for most recent statement affecting an AUTO_INCREMENT column by that client. This value cannot be affected by other clients, even if they generate AUTO_INCREMENT values of their own.

这意味着您可以放心地依赖 return 由 LAST_INSERT_ID() 编辑的值。它是由调用 LAST_INSERT_ID() 的同一代码实例生成的最新自动递增值。当然,您必须在要获取其值的 INSERT 语句之后立即调用它,它不能 return 由第二个最近的 INSERT 语句或更早的语句生成的值。