如何在MySQL中從特定點開始自動遞增?


要從特定點開始自動遞增,請使用ALTER命令。語法如下:

ALTER TABLE yourTableName auto_increment = anySpecificPoint;

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

mysql> create table AutoIncrementSpecificPoint
   −> (
   −> BookId int auto_increment not null,
   −> Primary key(BookId)
   −> );
Query OK, 0 rows affected (0.56 sec)

現在您可以使用insert命令插入記錄。

查詢如下:

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

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

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

mysql> insert into AutoIncrementSpecificPoint values();
Query OK, 1 row affected (0.10 sec)

上述insert命令從1開始,並在下一個值上加1。現在您可以使用select語句檢查表中的所有記錄。

查詢如下:

mysql> select *from AutoIncrementSpecificPoint;

以下是輸出:

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

檢視上面的示例輸出,auto_increment從1開始。

現在要更改auto_increment從特定點開始,可以使用ALTER命令。查詢如下:

mysql> alter table AutoIncrementSpecificPoint auto_increment = 100;
Query OK, 0 rows affected (0.25 sec)
Records: 0 Duplicates: 0 Warnings: 0

在上面的查詢中,我已將自動遞增設定為100。現在讓我們再次使用insert命令在表中插入記錄。查詢如下:

mysql> insert into AutoIncrementSpecificPoint values();
Query OK, 1 row affected (0.25 sec)

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

mysql> insert into AutoIncrementSpecificPoint values();
Query OK, 1 row affected (0.14 sec)

使用select語句顯示錶中的所有記錄。查詢如下:

mysql> select *from AutoIncrementSpecificPoint;

以下是顯示自動遞增的其他值的輸出,即從100開始:

+--------+
| BookId |
+--------+
|      1 |
|      2 |
|      3 |
|      4 |
|    100 |
|    101 |
|    102 |
+--------+
7 rows in set (0.00 sec)

更新於: 2019年7月30日

295 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告