MySQL 和 LAST_INSERT_ID() 返回错误 id 的可能性

发布于 2024-11-05 18:00:20 字数 347 浏览 0 评论 0原文

根据我的阅读,LAST_INSERT_ID() 检索要运行的最后一个插入语句的 id。如果最后一个插入语句在您的连接上运行,或者最后一个插入语句在所有连接的数据库上运行?我想我想问的是:在一个繁忙的数据库驱动的网站上,以下代码返回错误ID的可能性有多大,除了锁定数据库之外,是否有其他方法可以防止这种情况发生?

INSERT INTO example (string) VALUE ('something');
SELECT LAST_INSERT_ID();

PHP 的 mysql_insert_id() 是一个更好的解决方案,还是我应该查询刚刚插入的数据并以这种方式获取 id?

From what I have read LAST_INSERT_ID() retrieves the id of the last insert statement to run. If that the last insert statement run on your connection or the last insert run on the database for all connections? I guess what I am trying to ask is: on a busy database driven website what are the chances the following code would return the wrong id, and is there a method to prevent that other then locking the database?

INSERT INTO example (string) VALUE ('something');
SELECT LAST_INSERT_ID();

Would PHP's mysql_insert_id() be a better solution, or should I just query for data that was just inserted and grab id that way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

油焖大侠 2024-11-12 18:00:20

这是您的连接上运行的最后一个插入语句还是...

您的连接上的last_insert。

PHP 的 mysql_insert_id() 是一个更好的解决方案

?不,它是一样的。

或者我应该只查询刚刚插入的数据并以这种方式获取 id 吗?

这样慢得多

链接: http:// /dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id

引用该链接:

生成的 ID 会根据每个连接保存在服务器中。这意味着该函数返回给给定客户端的值是为该客户端影响 AUTO_INCRMENT 列的最新语句生成的第一个 AUTO_INCRMENT 值。该值不会受到其他客户端的影响,即使它们生成自己的 AUTO_INCRMENT 值。此行为确保每个客户端都可以检索自己的 ID,而无需关心其他客户端的活动,也不需要锁或事务。

Is that the last insert statement run on your connection or...

The last_insert on your connection.

Would PHP's mysql_insert_id() be a better solution

No, it's the same.

or should I just query for data that was just inserted and grab id that way?

That's way way slower

Link: http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id

Quote from that 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文