mysql 手动递增 ids?
我有一个表,其中包含项目(id、名称等),并且我希望某种数据库方案能够拥有该项目的多个副本,同时仍然能够增加 id。将有一个名为 startdate 或 date_from_which_this_entry_should_be_used 的字段。
我想到了两种实现此目的的方法:
拥有一个仅包含 ids(主键、自动增量)的表,并连接到包含所有项目信息的表。
优点:
- 简单易懂
- 在我之后的人很难感到困惑
缺点:
- 由于该系统已投入使用,因此需要更多调试和编码
- 拥有一个只有单个字段的表似乎很奇怪
拥有一个使用子表的表选择获取最大值 (+1) 以应用于新项目。
优点:
- 单表
- 仅进行细微的代码调整(但也许并没有那么不同)
缺点:
- 容易出错(手动递增、不允许删除或最大值可能已关闭)
提前致谢!
I have a table with items in it (id, name, etc) and I want some kind of database scheme to be able to have multiple copies of the item while still being able to increment the ids. There will be a field called startdate or date_from_which_this_entry_should_be_used.
I've thought of two ways of implementing this:
Have a table with only ids (primary key, auto-increment) and do joins to a table that has all the item information.
Advantages:
- easy to understand
- hard for someone that comes after me to get confused
Disadvantages:
- requires more debugging and coding since this system is already in use
- seems weird to have a table with a single field
Have a single table using a sub-select to get the MAX value (+1) to apply to new items.
Advantages:
- single table
- only minor code adjustments (but not all that different, maybe)
Disadvantages:
- prone to errors (manual increment, can't allow deletions or the MAX value might be off)
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该创建一个名为
item_ids
的表或其他表来生成 id 值。没关系,这只有一个列。您甚至不需要向其提交任何数据。您只需使用它来生成 id 值:
所以现在您有一个并发安全的方法来创建新的 id。
然后,您为
items
表创建一个复合主键。为此,您必须使用 MyISAM。MyISAM 支持复合主键中的自动增量列,对于每个新的
item_id
,该列将从值 1 开始。* 它还使用MAX(item_id)+1
,因此如果删除最后一个,其值将被重新分配。这与 AUTO_INCRMENT 的其他用途不同,在其他用途中,已删除的值不会重新使用。无论插入新项目,还是插入现有项目的新副本,都使用类似的 INSERT:
@id
参数要么是现有项目的值,要么是自动生成的值。您从item_ids
表中获取的生成值。* InnoDB 仅支持主键或唯一键的第一列自动递增,并且不会从其他列的每个不同值开始计数。
You should create a table called
item_ids
or something to generate id values. It's okay that this has only a single column.You don't even need to commit any data to it. You just use it to generate id values:
So now you have a concurrency-safe method to create new id's.
Then you make a compound primary key for your
items
table. You must use MyISAM for this.MyISAM supports an auto-increment column in a compound primary key, which will start over at value 1 for each new
item_id
.* It also usesMAX(item_id)+1
so if you delete the last one, its value will be reallocated. This is unlike other use of AUTO_INCREMENT where a deleted value is not re-used.Whether you insert a new item, or whether you insert a new copy of an existing item, you use a similar INSERT:
The
@id
parameter is either a value of an existing item, or else the auto-generated value you got from theitem_ids
table.* InnoDB supports auto-increment only as the first column of a primary or unique key, and it does not start over the count for each distinct value of the other column.