获取MySQL数据库表中AUTO_INCREMENT字段的下一个插入id

陪她去流浪 桃子 2015年07月22日 阅读次数:2389

在插入到MySQL数据库表中之前,有时候需要事先获取插入id以便完成一些跟插入id相关的操作,可以用以下方式完成。

MySQL把这些“相关信息”保存在数据库 `information_schema` 的表 `tables` 中,所以查询此表的相关字段即可。

该表的结构:

mysql> use information_schema;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> SHOW COLUMNS FROM tables;
+-----------------+---------------------+------+-----+---------+-------+
| Field           | Type                | Null | Key | Default | Extra |
+-----------------+---------------------+------+-----+---------+-------+
| TABLE_CATALOG   | varchar(512)        | NO   |     |         |       |
| TABLE_SCHEMA    | varchar(64)         | NO   |     |         |       |
| TABLE_NAME      | varchar(64)         | NO   |     |         |       |
| TABLE_TYPE      | varchar(64)         | NO   |     |         |       |
| ENGINE          | varchar(64)         | YES  |     | NULL    |       |
| VERSION         | bigint(21) unsigned | YES  |     | NULL    |       |
| ROW_FORMAT      | varchar(10)         | YES  |     | NULL    |       |
| TABLE_ROWS      | bigint(21) unsigned | YES  |     | NULL    |       |
| AVG_ROW_LENGTH  | bigint(21) unsigned | YES  |     | NULL    |       |
| DATA_LENGTH     | bigint(21) unsigned | YES  |     | NULL    |       |
| MAX_DATA_LENGTH | bigint(21) unsigned | YES  |     | NULL    |       |
| INDEX_LENGTH    | bigint(21) unsigned | YES  |     | NULL    |       |
| DATA_FREE       | bigint(21) unsigned | YES  |     | NULL    |       |
| AUTO_INCREMENT  | bigint(21) unsigned | YES  |     | NULL    |       |
| CREATE_TIME     | datetime            | YES  |     | NULL    |       |
| UPDATE_TIME     | datetime            | YES  |     | NULL    |       |
| CHECK_TIME      | datetime            | YES  |     | NULL    |       |
| TABLE_COLLATION | varchar(32)         | YES  |     | NULL    |       |
| CHECKSUM        | bigint(21) unsigned | YES  |     | NULL    |       |
| CREATE_OPTIONS  | varchar(255)        | YES  |     | NULL    |       |
| TABLE_COMMENT   | varchar(2048)       | NO   |     |         |       |
+-----------------+---------------------+------+-----+---------+-------+
21 rows in set (0.03 sec)

可以看到,表的名字、版本、创建时间、最后更新时间、AUTO_INCREMENT等都显示在这里了。

所以,要查询 AUTO_INCREMENT 的值就可以像这样:

mysql> SELECT AUTO_INCREMENT FROM information_schema.tables 
     > WHERE table_schema='数据库名' 
     > AND table_name = '表名';
+----------------+
| AUTO_INCREMENT |
+----------------+
|            539 |
+----------------+
1 row in set (0.00 sec)

参考

这篇文章的内容已被作者标记为“过时”/“需要更新”/“不具参考意义”。

标签:MySQL