我有一个包含 AUTO_INCRMENT
字段的表。 目前,它也是一个主键。
但是,在某些情况下,我需要此 AUTO_INCRMENT
列来允许重复。 换句话说 - 两个不同的行在 AUTO_INCRMENT 列中可以具有相同的值。 这意味着有一个不是主键的自动增量字段。
这可能吗?
我猜不是,因为每当我尝试这样做时,我都会收到此错误:
第 130 行错误 1075 (42000):表定义不正确; 只能有一个自动列,并且必须将其定义为键
我喜欢使用 AUTO_INCRMENT 字段,因为它使我不必在数据库中的其他位置手动存储/递增单独的计数器。 我可以插入表并获取插入的值。 但是,如果我不能有重复项,那么我似乎将不得不使用单独的表来跟踪和手动增加该字段。
更新:作为快速澄清,我已经熟悉将 AUTO_INCRMENT 字段与另一个键分组 如此处所述。 为了便于讨论,我们假设该解决方案由于数据库中的其他限制而无法工作。
I have a table that has an AUTO_INCREMENT
field. Currently, it is also a PRIMARY KEY.
However, there are situations where I need this AUTO_INCREMENT
column to permit duplicates. In other words - two different rows can have the same value inside the AUTO_INCREMENT
column. This would mean having an AUTO_INCREMENT field that is not a PRIMARY KEY.
Is this possible?
I'm guessing it's not, since whenever I try to do it, I get this error:
ERROR 1075 (42000) at line 130: Incorrect table definition; there can be only one auto column and it must be defined as a key
I like to have the AUTO_INCREMENT field because it saves me from having to manually store / increment a separate counter elsewhere in my database. I can just insert into the table and grab the value that was inserted. However, if I can't have duplicates, it seems like I'm going to be stuck with using a separate table to track and manually increment this field.
UPDATE: As a quick clarification, I am already familiar with grouping the AUTO_INCREMENT field with another key, as described here. Let's assume for the sake of argument that this solution won't work due to other constraints in the database.
发布评论
评论(2)
MySQL 中的自增字段必须是键(即索引)的一部分,但不一定是主键或唯一键的一部分。
An auto-increment field in MySQL must be part of a key (i.e. an index), but not necessarily part of a primary key or unique key.
听起来“子任务”是“任务”具有 FK 引用的表。 也就是说,如果子任务被重用。
OTOH,如果一项任务可以有许多子任务,并且一个子任务可以链接到多个任务,那么您将在单独的表中查看多对多。
无论哪种情况,我认为您都不希望数据库自动生成这些“链接 ID”。
Sounds like 'subtask' is a table to which 'task' has a FK reference to. That is, if subtasks are reused.
OTOH if a task can have many subtasks, and a subtask can be linked to more than one task then you're looking at many-to-many in a seperate table.
in either case I don't think you want the DB autogenerating these 'linked-IDs'.