修改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.