在 MYSQL 中,不新增新記錄就獲取下一個主鍵是否是不可能的


不,有可能在不新增新記錄的情況下獲取下一個主鍵。我們首先建立一個 -

mysql> create table DemoTable1399
   -> (
   -> StudentId int NOT NULL AUTO_INCREMENT,
   -> PRIMARY KEY(StudentId)
   -> );
Query OK, 0 rows affected (0.53 sec)

使用 insert 在表中插入一些記錄 -

mysql> insert into DemoTable1399 values();
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1399 values();
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1399 values();
Query OK, 1 row affected (0.07 sec)

使用 select 從表中顯示所有記錄 -

mysql> select * from DemoTable1399;

這將產生以下輸出 -

+-----------+
| StudentId |
+-----------+
|         1 |
|         2 |
|         3 |
+-----------+
3 rows in set (0.00 sec)

以下是對查詢以在不新增新記錄的情況下獲取下一個主鍵 -

mysql> select auto_increment as NextPrimaryKey
   -> from information_schema.tables
   -> where table_schema=database()
   -> and table_name = 'DemoTable1399';

這將產生以下輸出 -

+----------------+
| NextPrimaryKey |
+----------------+
|              4 |
+----------------+
1 row in set (0.00 sec)

更新時間:11-11-2019

46 瀏覽

開啟你的 職業

完成課程後獲得認證

開始
廣告
© . All rights reserved.