MySQL 如何获得下一个自增ID
MySQL有AUTO_INCREMENT关键字执行自动增长。 AUTO_INCREMENT的起始值为1,这是默认值。每个新记录将按1递增。
要在MySQL中获取下一个自动增量ID,我们可以使用MySQL的last_insert_id()函数或带有SELECT的auto_increment.
创建一个具有“id”自动递增的表。
mysql> create table NextIdDemo
-> (
-> id int auto_increment,
-> primary key(id)
-> );
Query OK, 0 rows affected (1.31 sec)
向表中插入记录。
mysql> insert into NextIdDemo values(1);
Query OK, 1 row affected (0.22 sec)
mysql> insert into NextIdDemo values(2);
Query OK, 1 row affected (0.20 sec)
mysql> insert into NextIdDemo values(3);
Query OK, 1 row affected (0.14 sec)
显示所有记录。
mysql> select *from NextIdDemo;
以下是输出。
+----+
| id |
+----+
| 1 |
| 2 |
| 3 |
+----+
3 rows in set (0.04 sec)
我们已插入3个记录。因此,下一个ID必须是4.
以下是语法以知道下一个ID。
SELECT AUTO_INCREMENT
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = "yourDatabaseName"
AND TABLE_NAME = "yourTableName"
以下是查询。
mysql> SELECT AUTO_INCREMENT
-> FROM information_schema.TABLES
-> WHERE TABLE_SCHEMA = "business"
-> AND TABLE_NAME = "NextIdDemo";
以下是显示下一个自动增长的输出。
+----------------+
| AUTO_INCREMENT |
+----------------+
| 4 |
+----------------+
1 row in set (0.25 sec)
阅读更多:MySQL 教程
极客教程