如何在 MySQL 中获取下一个自动递增 ID?
mysqlmysqli database
MySQL 具有 AUTO_INCREMENT 关键字来执行自动递增。AUTO_INCREMENT 的起始值为 1,这是默认值。每条新记录都会增加 1。
要在 MySQL 中获取下一个自动增量 ID,我们可以使用 MySQL 中的函数 last_insert_id() 或 auto_increment 与 SELECT。
创建一个表,将"d"作为自动增量。
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)