仅在需要时使用自动递增

Use auto increment only when needed

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

auto_increment 列确保其中的值是 唯一的!所以,你不能这样做。

我建议改用触发器,结合所需的逻辑。

对于 MyISAM tables,您可以在多列索引的辅助列上指定 AUTO_INCREMENT。在这种情况下,AUTO_INCREMENT 列的生成值计算为 MAX(auto_increment_column) + 1 WHERE prefix=given-prefix。当您想将数据放入有序组时,这很有用。

CREATE TABLE animals (
    grp ENUM('fish','mammal','bird') NOT NULL,
    id MEDIUMINT NOT NULL AUTO_INCREMENT,
    name CHAR(30) NOT NULL,
    PRIMARY KEY (grp,id)
) ENGINE=MyISAM;

INSERT INTO animals (grp,name) VALUES
    ('mammal','dog'),('mammal','cat'),
    ('bird','penguin'),('fish','lax'),('mammal','whale'),
    ('bird','ostrich');

SELECT * FROM animals ORDER BY grp,id;


Which returns:     
**grep   id name**     
fish   1  lax     
mammal 1  dog     
mammal 2  cat     
mammal 3  whale     
bird   1  penguin     
bird   2  ostrich      

如果 AUTO_INCREMENT 列是多个索引的一部分,MySQL 使用以 AUTO_INCREMENT 列开头的索引生成序列值(如果有的话)。例如,如果动物 table 包含索引 PRIMARY KEY (grp, id) 和 INDEX (id),则 MySQL 将忽略生成序列值的 PRIMARY KEY。因此,table 将包含单个序列,而不是每个 grp 值

的序列

正如 MySQL 关于 auto_increment 的文档所说(突出显示是我的):

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. 如果您可以并行插入 table,那么您可能必须锁定 table 才能读取,因此另一个进程不会插入新记录触发字段的增量。

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

备选方案是为 auto_increment 使用单独的 table,不要在主 table 中使用 auto_increment。如果您需要一个新的 ID,那么只需将一条记录插入 auto_ncrement table 并获取递增的 ID 并使用它在主 table 中插入一条记录。否则,只需从主 table 中获取 id 值并在插入中使用它。