MYSQL:SQL查询以获取autoincrement字段的值 [英] MYSQL: SQL query to get the value of autoincrement field

查看:198
本文介绍了MYSQL:SQL查询以获取autoincrement字段的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张桌子.主键为id,其自动递增. 现在,当我插入新记录时,我需要获取用于更新记录的ID. 我怎样才能做到这一点?如果我使用查询...

I have a table. The primary key is id and its auto incremented. Now when I insert a new record, I need to get the id with which the record was updated. How can I do that? If i use the query...

select max(id) from table_name

...执行后,我可以获得ID.但是我可以确定它是刚刚插入的记录的ID吗?因为很多人会同时使用该应用程序.

...after executing I can get the id. But can I be sure that its the id of the record that was just inserted? Because many people will be using the app at same time.

我正在使用php和mysql.

I am using php and mysql.

Ayone可以在mysql中为我提供一个示例代码片段吗?

Can ayone provie me a sample code snippet in php with mysql?

推荐答案

如果要从自动增量列中查找最新ID,只需运行

If you want to find out what the newest ID from an auto increment column is, you just have to run the mysql_insert_id() function right after your insert query.

像这样:

//--connection already made to database
//--now run your INSERT query on the table
mysql_query("INSERT INTO table_name (foo_column) VALUES ('everlong')");

//-- right after that previous query, you run this
$newest_id = mysql_insert_id();

现在$newest_id将包含插入的最新行的ID.

And now $newest_id will contain the ID of the latest row inserted.

这篇关于MYSQL:SQL查询以获取autoincrement字段的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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