首页 > 解决方案 > Do gaps in primary key slow down queries?

问题描述

I have a MySQL table where id is the primary key and auto-incremented.

Since I have a cron job that runs once per minute (updating stats from an external API) using ON DUPLICATE KEY, I'm finding a lot of gaps in the id column. I have one column set to be unique, obviously that's what is causing the gaps.

For example, there's only 183 rows, but I'm already at 71511 for the id column.

The only SELECT query I run is similar to this:

SELECT * FROM table WHERE member = '123' ORDER BY id DESC LIMIT 30

I don't care that the number is getting high quickly and it's not used anywhere else. I'm just trying to find out if it'll cause queries to be slower over time.

For example, if I had a table with 100,000 rows but the id is at a billion, would the gaps cause inserts or selects to run slower?

标签: mysqlsql

解决方案


不,存在差距是因为通过这种方式计算唯一标识符来处理并发系统更快更容易。

您的 auto_increment 的值是否1755131性能目的无关。

存储要求由您的表定义,自动增量最常用的存储标识符是 4-byte int。无论您存储什么数字,它都占用 4 个字节(当然,如果它可以容纳 4 个字节)。

出现差距以及为什么它们不是问题是有原因的。Primary key是唯一标识符。计算唯一标识符的最简单方法是每次更改表(插入、删除)时递增一个数字。

这个数字不需要是连续的,而是唯一的。MySQL 使用顺序算法来计算唯一编号。

由于 MySQL 在运行时考虑到并发性,因此每个事务都是隔离的(如果使用事务引擎)。如果事务导致 auto_increment 发生更改但未能写入 - auto_increment 将永远使用。每个表都有一个计数器,没有检查数字是否应该下降的代码(这很浪费资源)——它只会上升,不管查询是否成功。

这种方法保证:

  1. 性能 - 无需担心计数器的状态应该是什么(它是否应该下降)

  2. 唯一性 - 这是计算行唯一标识符的最快和最安全的方法 - 只需将数字递增auto_increment_offset. 无需担心碰撞等等。您 100% 确定,如果您将最后一个数字增加auto_increment_offset- 您将在数据库中获得一个新的、唯一且未使用的数字/

对于数据库,尤其是 MySQL,在写入或读取性能方面存在各种因素。最小化和试图摆弄auto_increment不是其中之一。如果你保持一切原样,你会没事的。

如果您认为您将超过 4 字节无符号整数的最大值(大约 42 亿),您可以考虑将主键更改为bigint. 如果你每秒插入数千条记录,你不会超过几千年。


推荐阅读