MySQL和LAST_INSERT_ID()返回错误ID的机会 [英] MySQL and the chance of the wrong id being returned by LAST_INSERT_ID()

查看:222
本文介绍了MySQL和LAST_INSERT_ID()返回错误ID的机会的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我所读的内容LAST_INSERT_ID()检索要运行的最后一个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();

PHP的mysql_insert_id()是一个更好的解决方案,还是我应该只查询刚刚插入的数据并以这种方式获取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?

推荐答案

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

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

您连接上的last_insert.

The last_insert on your connection.

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

Would PHP's mysql_insert_id() be a better solution

不,是相同的.

还是我应该只查询刚刚插入的数据并以这种方式获取ID?

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

那就慢了

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

从该链接引用:

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

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.

这篇关于MySQL和LAST_INSERT_ID()返回错误ID的机会的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆