如何重置 MySQL 表的主鍵?


重置表的 primary key 是指將 auto_increment 屬性重置為 1。以下是在 MySQL 中重置表主鍵的語法。

alter table yourTableName auto_increment = 1;

為了便於理解,我們先建立一個表 −

mysql> create table ResetPrimaryKey
−> (
   −> Id int auto_increment,
   −> PRIMARY KEY(Id)
−> );
Query OK, 0 rows affected (0.59 sec)

向表中插入一些記錄。插入記錄的查詢如下 −

mysql> insert into ResetPrimaryKey values();
Query OK, 1 row affected (0.18 sec)

mysql> insert into ResetPrimaryKey values();
Query OK, 1 row affected (0.15 sec)

mysql> insert into ResetPrimaryKey values();
Query OK, 1 row affected (0.09 sec)

mysql> insert into ResetPrimaryKey values();
Query OK, 1 row affected (0.09 sec)

現在,你可以使用 select 語句顯示所有記錄。查詢如下 −

mysql> select *from ResetPrimaryKey;

以下僅顯示 ID 的輸出,ID 是主鍵

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

這裡是對錶使用 alter 重置主鍵的查詢 −

mysql> alter table ResetPrimaryKey auto_increment = 1;
Query OK, 0 rows affected (0.21 sec)
Records: 0 Duplicates: 0 Warnings: 0

檢查是否成功添加了 auto_increment 屬性的查詢

mysql> desc ResetPrimaryKey;

以下是輸出 −

+-------+---------+------+-----+---------+----------------+
| Field | Type    | Null | Key | Default | Extra          |
+-------+---------+------+-----+---------+----------------+
| Id    | int(11) | NO   | PRI | NULL    | auto_increment |
+-------+---------+------+-----+---------+----------------+
1 row in set (0.11 sec)

更新於: 2020 年 6 月 29 日

931 次瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

開始學習
廣告
© . All rights reserved.