mysql - 仅在需要时使用自动递增

标签 mysql insert auto-increment

我的数据库 "id"int(11) NOT NULL AUTO_INCREMENT, 中有一列,我希望此表中的多行具有相同的 id 值。因此,当插入到表中时,我想告诉它是应该增加还是值保持不变。有什么简单的方法可以做到这一点吗?

最佳答案

作为 auto_increment 上的 MySQL 文档说(突出显示是我的):

No value was specified for the AUTO_INCREMENT column, so MySQL assigned sequence numbers automatically. You can also explicitly assign 0 to the column to generate sequence numbers, unless the NO_AUTO_VALUE_ON_ZERO SQL mode is enabled. If the column is declared NOT NULL, it is also possible to assign NULL to the column to generate sequence numbers. When you insert any other value into an AUTO_INCREMENT column, the column is set to that value and the sequence is reset so that the next automatically generated value follows sequentially from the largest column value.

这意味着,如果您在插入之前确定 auto_increment 字段的当前最大值,并在插入语句中显式插入该值,那么您可以在 auto_increment 字段中有重复值。

有几点需要注意:

  1. 如果您可以对表进行并行插入,那么您可能必须锁定表以供读取,因此另一个进程不会插入新记录来触发字段的递增。

  2. 您不能在 auto_increment 字段上使用主/唯一索引约束。

另一种方法是为 auto_increment 使用一个单独的表,而不在主表中使用 auto_increment。如果您需要一个新的 id,那么只需将一条记录插入到 auto_ncrement 表中,获取递增的 id 并使用它来将一条记录插入到主表中。否则,只需从主表中获取 id 值并在插入中使用它。

关于mysql - 仅在需要时使用自动递增,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40863565/

相关文章:

mysql - SQL 更新依赖于同一个表中最后一条记录的字段

php - 如果尚未添加到数据库,如何获取 ID? (mysql)

c++ - 将 std::unique_ptr 插入 std::set

MySQL "simple"错误理解

mysql - 我想显示包含给定成分但也有其他成分的食谱

sql - 如何在 SQL Server 中插入前导零

MySQL ID 列

google-app-engine - App Engine 数据存储中的自动增量 ID

database - Postgres 序列值递增 2

mysql - SQL语句为joomla文章数据库创建基于另一个字段的字段