如何在 MySQL 中獲取下一個自動增量 ID?


MySQLAUTO_INCREMENT 關鍵字來執行自動增量。AUTO_INCREMENT 的起始值是 1,這是預設值。對於每條新記錄,它將增加 1。

要獲取 MySQL 中的下一個自動增量 ID,我們可以使用 來自 MySQL 的 last_insert_id() 函式 或帶 SELECT 的 AUTO_INCREMENT。

建立一個表,其中“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";

以下是顯示下一個自動增量 ID 的輸出。

+----------------+
| AUTO_INCREMENT |
+----------------+
|              4 |
+----------------+
1 row in set (0.25 sec)

更新時間: 2023-年9月-14日

31K+ 瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.