如何处理 MySQL 中自动增量 ID 列的碎片?
mysqlmysqli database
每当我们重新编号时,可能会出现问题。需要为列声明一个唯一的 ID。
在 MySQL 5.6 版 InnoDB 中,我们可以通过在 INSERT 语句中包含 ID 列来重用自动增量 ID,并且可以提供我们想要的任何特定值。
情况如下 −
- 每当我们删除具有最高数字的 ID 时
- 每当我们启动和停止 MySQL 服务器时
- 每当我们插入新记录时
使用 auto_increment 变量的 ID 自动增量示例。
mysql> create table UniqueAutoId -> ( -> id int auto_increment, -> Unique(id) -> ); Query OK, 0 rows affected (0.45 sec)
将记录插入表中。
mysql> insert into UniqueAutoId values(); Query OK, 1 row affected (0.13 sec) mysql> insert into UniqueAutoId values(); Query OK, 1 row affected (0.16 sec) mysql> insert into UniqueAutoId values(); Query OK, 1 row affected (0.07 sec) mysql> insert into UniqueAutoId values(); Query OK, 1 row affected (0.10 sec) mysql> insert into UniqueAutoId values(); Query OK, 1 row affected (0.10 sec)
显示所有记录。
mysql> select *from UniqueAutoId;
以下是输出。
+----+ | id | +----+ | 1 | | 2 | | 3 | | 4 | | 5 | +----+ 5 rows in set (0.00 sec)
要删除记录,我们使用 DELETE 语句。这里我们删除 id=5;
mysql> DELETE from UniqueAutoId where id=5; Query OK, 1 row affected (0.14 sec)
显示所有记录。
mysql> select *from UniqueAutoId;
以下是输出。
+----+ | id | +----+ | 1 | | 2 | | 3 | | 4 | +----+ 4 rows in set (0.00 sec)
让我们再次从表中删除一条记录。
mysql> delete from UniqueAutoId where id=2; Query OK, 1 row affected (0.15 sec)
再次显示表中的记录。
mysql> select *from UniqueAutoId;
以下是输出。
+----+ | id | +----+ | 1 | | 3 | | 4 | +----+ 3 rows in set (0.00 sec
上述情况将导致碎片化。