如何在MySQL中將表的自增值設定為較低的值?


如果您使用的是InnoDB引擎,則無法將表的auto_increment值設定為較低的值。您需要將引擎從InnoDB更改為MyISAM。

注意:MyISAM引擎允許您設定較低的值。這裡我們使用的是相同的引擎。

根據官方文件

You cannot reset the counter to a value less than or equal to any that have
already been used. For MyISAM, if the value is less than or equal to the
maximum value currently in the AUTO_INCREMENT column, the value is reset
to the current maximum plus one. For InnoDB, if the value is less than the
current maximum value in the column, no error occurs and the current sequence
value is not changed.

如上所示,在MyISAM中,假設一些ID被刪除了。之後,如果您再次新增auto_increment,則ID將從較低的值開始,即從剩餘的最終ID開始(在我們刪除一些ID之後)。

讓我們首先建立一個使用MyISAM引擎的表。

mysql> create table DemoTable (Id int NOT NULL AUTO_INCREMENT PRIMARY KEY)ENGINE='MyISAM';
Query OK, 0 rows affected (0.23 sec)

以下是使用insert命令向表中插入記錄的查詢。

mysql> insert into DemoTable values();
Query OK, 1 row affected (0.04 sec)
mysql> insert into DemoTable values();
Query OK, 1 row affected (0.03 sec)
mysql> insert into DemoTable values();
Query OK, 1 row affected (0.03 sec)
mysql> insert into DemoTable values();
Query OK, 1 row affected (0.02 sec)
mysql> insert into DemoTable values();
Query OK, 1 row affected (0.05 sec)
mysql> insert into DemoTable values();
Query OK, 1 row affected (0.08 sec)

以下是使用select命令從表中顯示記錄的查詢。

mysql> select *from DemoTable;

這將產生以下輸出。

+----+
| Id |
+----+
|  1 |
|  2 |
|  3 |
|  4 |
|  5 |
|  6 |
+----+
6 rows in set (0.00 sec)

現在,刪除ID 4、5和6。

mysql> delete from DemoTable where Id=4 or Id=5 or Id=6;
Query OK, 3 rows affected (0.06 sec)

讓我們再次顯示所有記錄。以下是查詢。

mysql> select *from DemoTable;

刪除一些ID後,將產生以下輸出。

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

現在,讓我們設定新的auto_increment ID。

以下是將MyISAM引擎中的auto_increment值設定為較低值的查詢。但是,當前的auto_increment值現在應該從7開始,但是由於我們使用的是MyISAM引擎,因此該值將重置為當前最大值,即3加1,也就是3+1=4將是新的ID。

以下是查詢。

mysql> alter table DemoTable auto_increment=4;
Query OK, 3 rows affected (0.38 sec)
Records: 3 Duplicates: 0 Warnings: 0

現在再次插入一些記錄,然後顯示錶中的所有記錄以檢查auto_increment值是否從4開始。

mysql> insert into DemoTable values();
Query OK, 1 row affected (0.03 sec)
mysql> insert into DemoTable values();
Query OK, 1 row affected (0.06 sec)
mysql> insert into DemoTable values();
Query OK, 1 row affected (0.02 sec)

以下是顯示錶中所有記錄的查詢。

mysql> select *from DemoTable;

這將產生以下輸出。新的ID從4開始。

+----+
| Id |
+----+
|  1 |
|  2 |
|  3 |
|  4 |
|  5 |
|  6 |
+----+
6 rows in set (0.00 sec)

更新於:2019年7月30日

730 次瀏覽

啟動您的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.