重置 MySQL 中的主鍵
要重置主鍵,一開始使用 TRUNCATE 表格,然後使用 ALTER TABLE。讓我們首先建立一個表 -
mysql> create table DemoTable1929 ( UserId int NOT NULL AUTO_INCREMENT, PRIMARY KEY(UserId) ); Query OK, 0 rows affected (0.00 sec)
使用 insert 命令在表中插入一些記錄 -
mysql> insert into DemoTable1929 values(); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1929 values(); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1929 values(); Query OK, 1 row affected (0.00 sec)
使用 select 語句顯示錶中的所有記錄 -
mysql> select * from DemoTable1929;
將生成以下輸出 -
+--------+ | UserId | +--------+ | 1 | | 2 | | 3 | +--------+ 3 rows in set (0.00 sec)
以下是重置主鍵的查詢 -
mysql> truncate table DemoTable1929; Query OK, 0 rows affected (0.00 sec) mysql> alter table DemoTable1929 auto_increment=1; Query OK, 0 rows affected (0.00 sec) Records: 0 Duplicates: 0 Warnings: 0
現在您可以插入記錄,它會將主鍵值從 1 開始重置 -
mysql> insert into DemoTable1929 values(); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1929 values(); Query OK, 1 row affected (0.00 sec)
使用 select 語句顯示錶中的所有記錄 -
mysql> select * from DemoTable1929;
將生成以下輸出 -
+--------+ | UserId | +--------+ | 1 | | 2 | +--------+ 2 rows in set (0.00 sec)
廣告