MySQL 自动递增和 select 计数

MySQL auto increment and select count

我遇到了一个关于 MySQL 查询的奇怪问题,我有一个 table 字段

slno,mobileno , contractor with slno as primary key and auto increment sequence 1

,虽然测试说 uptil 100 记录计数和自动增量值相同,

所以我截断了 table 以重置自动增量并通过 php 插入了一个包含大约 40k 数据的巨大 excel 文件,然后发出 select 查询产生

the max of slno is 40000 as expected but the count shows 39920

,我只是被逗乐并试图找到 google ,可能是我缺乏关键字搜索能力阻止了我找到结果,所以我在这里发帖,以供参考添加屏幕截图,任何想法和澄清。谢谢

编辑: 最小 slno 为 1

编辑: 在 mysql 中找到自动编号差距的解决方案的相关问题是 asked and solved here

种特定情况下 auto-incremented 值可能会丢失。一个例子是如果你回滚一个插入。根据 doco:

"Lost" auto-increment values and sequence gaps

In all lock modes (0, 1, and 2), if a transaction that generated auto-increment values rolls back, those auto-increment values are "lost". Once a value is generated for an auto-increment column, it cannot be rolled back, whether or not the "INSERT-like" statement is completed, and whether or not the containing transaction is rolled back. Such lost values are not reused. Thus, there may be gaps in the values stored in an AUTO_INCREMENT column of a table.

在那种情况下,虽然插入被取消,但 auto-increment 可能不会。这肯定会允许您从 Excel 批量插入的可能性偶尔会失败并重试,随后重试工作。这实际上取决于您的插入过程如何运作。


无论如何,假设这些值总是连续的实际上是一个糟糕的假设。

这是因为,即使插入 保证是连续的,也有可能 删除 行,这会导致出现间隙。您当然可以在每次删除(或批量插入)时修复此问题,但工作量很大 - 您基本上必须找到间隙,然后将更高的条目“移动”到这些间隙中。

此移动很可能是 non-trivial,因为很可能会有其他表保存该列的键 look-ups,并且每个表都需要更改。

因此,auto-increment 字段的最佳用例是简单地为不存在其他字段的行提供唯一标识符,并且 不必 必须连续。