如何在 MySQL 中将表的自动增量值设置为较低的值?

mysqlmysqli database

如果您使用的是 InnoDB 引擎,则无法将表的自动增量值设置为较低的值。您需要将引擎从 InnoDB 更改为 MyISAM。

注意:引擎 MyISAM 允许您设置较低的值。这里,我们使用相同的引擎。

根据官方文档:

You cannot reset the counter to a value less than or equal to any that have
already been used. For MyISAM, if the value is less than or equal to the
maximum value currently in the AUTO_INCREMENT column, the value is reset
to the current maximum plus one. For InnoDB, if the value is less than the
current maximum value in the column, no error occurs and the current sequence
value is not changed.

如上所示,在 MyISAM 中,假设删除了一些 ID。之后,如果您再次添加 auto_increment,则 ID 将从较低的值开始,即从最后剩余的 ID 开始(在我们删除一些 ID 之后)。

Let us first create a table with engine MyISAM:

mysql> create table DemoTable (Id int NOT NULL AUTO_INCREMENT PRIMARY KEY)ENGINE='MyISAM';
Query OK, 0 rows affected (0.23 sec)

以下是使用 insert 命令在表中插入记录的查询:

mysql> insert into DemoTable values();
Query OK, 1 row affected (0.04 sec)
mysql> insert into DemoTable values();
Query OK, 1 row affected (0.03 sec)
mysql> insert into DemoTable values();
Query OK, 1 row affected (0.03 sec)
mysql> insert into DemoTable values();
Query OK, 1 row affected (0.02 sec)
mysql> insert into DemoTable values();
Query OK, 1 row affected (0.05 sec)
mysql> insert into DemoTable values();
Query OK, 1 row affected (0.08 sec)

以下是使用 select 命令显示表中记录的查询:

mysql> select *from DemoTable;

这将产生以下输出 −

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

现在,删除 ID 4、5 和 6:

mysql> delete from DemoTable where Id=4 or Id=5 or Id=6;
Query OK, 3 rows affected (0.06 sec)

让我们再次显示所有记录。以下是查询:

mysql> select *from DemoTable;

删除一些 ID 后,将产生以下输出:

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

现在,让我们设置新的 auto_increment id。

以下是在 MyISAM 引擎中将 auto_increment 值设置为较低的查询。但是,当前的 auto_increment 值现在应该从 7 开始,但由于我们使用的是 MyISAM 引擎,因此该值将重置为当前最大值,即 3 加 1,即 3+1 = 4 将是新的 id。

以下是查询:

mysql> alter table DemoTable auto_increment=4;
Query OK, 3 rows affected (0.38 sec)
Records: 3 Duplicates: 0 Warnings: 0

现在再次插入一些记录,然后显示表中的所有记录以检查 auto_increment 值是否从 4 开始:

mysql> insert into DemoTable values();
Query OK, 1 row affected (0.03 sec)
mysql> insert into DemoTable values();
Query OK, 1 row affected (0.06 sec)
mysql> insert into DemoTable values();
Query OK, 1 row affected (0.02 sec)

以下是显示表中的所有记录的查询:

mysql> 从 DemoTable 中选择 *;

这将产生以下输出。新的 ID 从 4 开始:

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

相关文章