简体   繁体   English

如何准确获取mysql中最后插入的记录的id?

[英]How to get exactly the id of the last inserted record in mysql?

I am building a web application, which can be used by multiple users simultaneously. 我正在构建一个Web应用程序,可以由多个用户同时使用。 They can add data at the same time. 他们可以同时添加数据。

I have a table named doctor_main as follows 我有一个名为doctor_main的表如下

Screenshot of DB http://img687.imageshack.us/img687/7033/testxqz.png DB的屏幕截图http://img687.imageshack.us/img687/7033/testxqz.png

Once a record about a doctor is added, I want the id of the inserted record(which is an auto increment field) to be returned. 一旦添加了关于医生的记录,我想要返回插入记录的id(这是一个自动增量字段)。

I know i can use methods like LAST_INSERT_ID() and mysql_insert_id. 我知道我可以使用像LAST_INSERT_ID()和mysql_insert_id这样的方法。 But i don't know how it behaves. 但我不知道它是如何表现的。

I need the exact id of the record which is inserted by that particular user. 我需要该特定用户插入的记录的确切ID。

Sometimes, if two users are trying to insert a record, the id which is returned shouldn't get exchanged. 有时,如果两个用户试图插入记录,则不应交换返回的id。

To achieve this what kind of mysql function should i use ? 要实现这一点,我应该使用什么样的mysql函数?

There's a whole page in the manual dedicated to this subject: 手册中有一整页专门讨论这个主题:

Here's a quote from that page that should help answer your question: 以下是该页面的引用,可以帮助回答您的问题:

For LAST_INSERT_ID(), the most recently generated ID is maintained in the server on a per-connection basis. 对于LAST_INSERT_ID(),最近生成的ID基于每个连接在服务器中维护。 It is not changed by another client. 它不会被其他客户更改。

mysql_insert_id()完全返回最后插入记录的id,所以如果你只是echo mysql_insert_id()你将得到最后一个插入行的id。

根据文档mysql_insert_id将返回您之前完成的插入的确切ID。

LAST_INSERT_ID() and mysql_insert_id works fine. LAST_INSERT_ID()mysql_insert_id工作正常。 Each client will receive the last inserted ID for the last statement that client executed. 每个客户端将接收客户端执行的最后一个语句的最后插入的ID

LAST_INSERT_ID() operates per-connection; LAST_INSERT_ID()按连接操作; multiple users will use multiple connections, so there will never be an exchange of IDs between users. 多个用户将使用多个连接,因此用户之间永远不会交换ID。

如果您对last_insert_id的机制持怀疑last_insert_id ,那么您可以手动分配id而不是MySQL的auto_increment功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM