我需要在 MySQL 中自动递增一个非主键字段
现在,我有一个表,其主键是 auto_increment
字段。 但是,我需要将主键设置为用户名
,日期
(以确保不能有重复的用户名和日期)。
但是,我需要 auto_increment
字段,以便更改行信息(添加和删除)。
遇到这种情况通常该怎么办?
谢谢!
Right now, I have a table whose primary key is an auto_increment
field. However, I need to set the primary key as username
, date
(to ensure that there cannot be a duplicate username with a date).
I need the auto_increment
field, however, in order to make changes to row information (adding and deleting).
What is normally done with this situation?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
只需在(用户名,日期)的组合上设置唯一索引即可。
或者,您可以尝试
,我认为在后一种情况下您需要将这些列声明为 NOT NULL。
Just set a unique index on composite of (username, date).
Alternatively, you can try to
and I think in the latter case you need those columns to be declared NOT NULL.
我知道这是老问题,这就是我解决问题的方法 -
I know this is old question, here is how i solved the problem -
使用类似的内容:
如果您已经有了表,并且只想添加唯一约束
用户+日期,运行
Use something like:
If you already have the table, and just want to add a unique constraint on
user+thedate, run
将当前主键更改为唯一键:
此后 auto_increment 将正常运行,不会出现任何问题。 您还应该在 auto_increment 字段上放置一个唯一键,以用于行处理:
Change your current primary key to be a unique key instead:
The auto_increment will function normally after that without any problems. You should also place a unique key on the auto_increment field as well, to use for your row handling: