在 MySQL 中刪除所有資料後把主鍵重置為 1?
要刪除資料後把主鍵重置為 1,請使用以下語法
alter table yourTableName AUTO_INCREMENT=1; truncate table yourTableName;
執行以上兩個步驟後,您將從 1 開始獲取主鍵。
為了理解上述概念,讓我們建立一個表。建立表的查詢如下
mysql> create table resettingPrimaryKeyDemo -> ( -> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY -> ); Query OK, 0 rows affected (0.66 sec)
使用插入命令在表中插入一些記錄。查詢如下 −
mysql> insert into resettingPrimaryKeyDemo values(); Query OK, 1 row affected (0.15 sec) mysql> insert into resettingPrimaryKeyDemo values(); Query OK, 1 row affected (0.10 sec) mysql> insert into resettingPrimaryKeyDemo values(); Query OK, 1 row affected (0.08 sec) mysql> insert into resettingPrimaryKeyDemo values(); Query OK, 1 row affected (0.12 sec)
使用選擇語句顯示錶中的所有記錄。查詢如下 −
mysql> select *from resettingPrimaryKeyDemo;
以下是輸出
+--------+ | UserId | +--------+ | 1 | | 2 | | 3 | | 4 | +--------+ 4 rows in set (0.00 sec)
以下是把主鍵重置為 1 的查詢
mysql> alter table resettingPrimaryKeyDemo AUTO_INCREMENT=1; Query OK, 0 rows affected (0.14 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> truncate table resettingPrimaryKeyDemo; Query OK, 0 rows affected (0.89 sec)
檢查表中的記錄。查詢如下 −
mysql> select *from resettingPrimaryKeyDemo; Empty set (0.00 sec)
使用插入命令從表中插入一些記錄。查詢如下 −
mysql> insert into resettingPrimaryKeyDemo values(); Query OK, 1 row affected (0.12 sec) mysql> insert into resettingPrimaryKeyDemo values(); Query OK, 1 row affected (0.10 sec) mysql> insert into resettingPrimaryKeyDemo values(); Query OK, 1 row affected (0.10 sec)
現在檢查表從 1 開始的主鍵。查詢如下 −
mysql> select *from resettingPrimaryKeyDemo;
以下是輸出
+--------+ | UserId | +--------+ | 1 | | 2 | | 3 | +--------+ 3 rows in set (0.00 sec)
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP