gpt4 book ai didi

MySQL LAST_INSERT_ID() 题潜

转载 作者:行者123 更新时间:2023-11-29 01:49:15 27 4
gpt4 key购买 nike

例如,如果我有插入查询:

INSERT INTO user(username) VALUES('admin');

然后用

获取插入记录的id
LAST_INSERT_ID();

看起来找到了,但是如果在插入和 LAST_INSERT_ID() 之间执行另一个插入会发生什么。

MySQL 如何知道返回正确的 ID(对于第一次或第二次插入),因为没有参数传递给 LAST_INSERT_ID();

用这个功能省事吗?

谢谢

最佳答案

我假设你的意思是如果我连接到 MySQL 服务器并执行 INSERT 但其他人也在执行插入,比如在客户端当前正在使用它时更新网站上的表,会发生什么情况。

如果你去看看文档 https://dev.mysql.com/doc/refman/8.0/en/information-functions.html有一点可以回答你的问题:

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.

这在 MariaDB 中应该是相同的。

正如评论中所讨论的,您想知道是否可以在 php PDO 环境中使用它。如果您打算直接从数据库中使用它,那就不行,您将无法获得最后插入的 ID,因为您将没有与 PDO 相同的客户端连接。如果您想直接从 PDO 使用它,请使用特定的 PDO 函数: http://php.net/manual/fr/pdo.lastinsertid.php ,这应该允许做你想做的事。

关于MySQL LAST_INSERT_ID() 题潜,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52620647/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com