MySQL 访问mysql中最后插入的行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12600527/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Accessing last inserted row in mysql
提问by clint
On my db-server i am inserting data in a table having a auto increment field say 'id'. Now i want to use the value of this last inserted 'id' in subsequent steps. I can use this:-
在我的数据库服务器上,我在一个表中插入数据,该表有一个自动增量字段,比如“id”。现在我想在后续步骤中使用最后插入的“id”的值。我可以用这个:-
select * from table_name order by id desc limit 1;
But the problem here is, it is a server and many more insertions could be happening and there could be a case where i try to retrieve the data with the query i mentioned and get a different id ie. between my insert and select there could be some other insert and i wont get the value i inserted. Any way in which this could be addressed.?
但这里的问题是,它是一个服务器,可能会发生更多插入,并且可能会出现我尝试使用我提到的查询检索数据并获得不同 ID 的情况,即。在我的插入和选择之间可能有一些其他插入,我不会得到我插入的值。有什么办法可以解决这个问题。?
Thanks in advance.
提前致谢。
采纳答案by chhameed
Use this
用这个
mysql_insert_id(&mysql);
as its basic structure are
因为它的基本结构是
mysql_insert_id ([ resource $link_identifier = NULL ] )
Retrieves the ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT).
检索前一个查询(通常是 INSERT)为 AUTO_INCREMENT 列生成的 ID。
or in mysql use
或在 mysql 中使用
SELECT LAST_INSERT_ID();
here is the ref links
这是参考链接
http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html
http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html
回答by user786
Use this mysql_insert_id()
使用这个mysql_insert_id()
It returns the AUTO_INCREMENT ID generated from the previous INSERT operation.
它返回从前一个 INSERT 操作生成的 AUTO_INCREMENT ID。
This function returns 0 if the previous operation does not generate an AUTO_INCREMENT ID, or FALSE on MySQL connection failure.
如果前一个操作没有生成 AUTO_INCREMENT ID,则此函数返回 0,或者在 MySQL 连接失败时返回 FALSE。
回答by moCap
call LAST_INSERT_ID()
function immediately after insertion and save id somewhere.
LAST_INSERT_ID()
插入后立即调用函数并将 id 保存在某处。
回答by user1626936
you can get the id if you call LAST_INSERT_ID() function immediately after insertion and then you can use it.
如果您在插入后立即调用 LAST_INSERT_ID() 函数,您可以获得 id 然后您可以使用它。
回答by kaushik kyada
For any last inserted record will be get through mysql_insert_id()If your table contain any AUTO_INCREMENT column it will return that Value.
对于任何最后插入的记录,将通过mysql_insert_id()获取 如果您的表包含任何 AUTO_INCREMENT 列,它将返回该值。
mysql_query("INSERT INTO test(emsg,etime) values ('inserted',now())");
printf("Last inserted record has id %d\n", mysql_insert_id());
$last_id=mysql_insert_id();
echo $last_id;
?>