在 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)

更新於: 2019-07-30

8K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得證書

開始
廣告
© . All rights reserved.