如何在MySQL中获取下一个自增ID?

WBOY
WBOY 转载
2023-08-22 22:29:05 871浏览

如何在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中获取下一个自增ID?的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除