修改MySQL中自動增量值的當前計數?


可以使用ALTER命令更改MySQL中auto_increment的當前計數。

語法如下:

ALTER TABLE yourTableName AUTO_INCREMENT = IntegerValue;

為了理解上述語法,讓我們建立一個表。建立表的查詢如下:

mysql> create table changeCurrentAutoIncrementValue
   −> (
   −> CurrentCount int auto_increment,
   −> PRIMARY KEY(CurrentCount)
   −> );
Query OK, 0 rows affected (0.60 sec)

使用select語句在表中插入記錄。auto_increment預設從1開始,每次遞增1。插入記錄的查詢如下:

mysql> insert into changeCurrentAutoIncrementValue values();
Query OK, 1 row affected (0.20 sec)

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

mysql> insert into changeCurrentAutoIncrementValue values();
Query OK, 1 row affected (0.11 sec)

mysql> insert into changeCurrentAutoIncrementValue values();
Query OK, 1 row affected (0.12 sec)

Display all records to check from where the value starts. The query is as follows:

mysql> select *from changeCurrentAutoIncrementValue;

以下是輸出結果

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

檢視上面的示例輸出,auto_increment從1開始,下一個數字是前一個數字加1生成的。

以下是更改當前auto_increment值的查詢:

mysql> alter table changeCurrentAutoIncrementValue auto_increment = 300;
Query OK, 0 rows affected (0.27 sec)
Records: 0 Duplicates: 0 Warnings: 0

檢視上面的查詢。我們已經更改了auto_increment值。現在它從300開始。新的值將新增到上述值之後,即4之後。

現在讓我們再次在表中插入記錄。查詢如下:

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

mysql> insert into changeCurrentAutoIncrementValue values();
Query OK, 1 row affected (0.17 sec)

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

顯示錶中的記錄以進行檢查。查詢如下:

mysql> select *from changeCurrentAutoIncrementValue;

以下是輸出結果:

+--------------+
| CurrentCount |
+--------------+
|            1 |
|            2 |
|            3 |
|            4 |
|          300 |
|          301 |
|          302 |
+--------------+
7 rows in set (0.00 sec)

檢視上面的示例輸出,更改auto_increment值後,值從300開始。

更新於:2019年7月30日

412 次瀏覽

啟動您的職業生涯

完成課程後獲得認證

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