如何在 MySQL 中獲取下一個自動增量 ID?
MySQL 有 AUTO_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)
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP