MySQL 用递增值填充新列而不使用 auto_increment
我看到很多几乎类似的问题都有明显的答案,但我相当确定这个问题还没有在这里。
我需要在现有表中添加一个自动递增的 id 列并将其设置为主键。我不能丢失任何现有数据。
我可以成功地更改表结构,但收到有关新列中的截断数据的错误。当我查看数据时,新的自动递增列中的每个值都是空(因此不是唯一的)。
如何回填这些值以确保主键的唯一性?
***如果有更简单的解决方案,我宁愿避免将现有数据转储到临时表并重新插入。
当前脚本:
alter table the_table add new_field int first;
alter table the_table drop primary key, add primary key (new_field);
alter table the_table change new_field new_field int unsigned not null auto_increment;
我按此顺序运行脚本,因为我不能拥有不是主键的自动递增列。
(MySQL 5.3)
I see lots of almost similar questions with obvious answers but I'm fairly sure this question isn't already on here.
I need to add an auto-incrementing id column to an existing table and set it as the primary key. I can't lose any of the existing data.
I can successfully make the change to the table structure but I get an error about truncated data in the new column. When I view the data every value in the new auto-incrementing column is null (and therefore not unique).
How can I back-fill these values to ensure uniqueness in my primary key?
***I would prefer to avoid dumping the existing data to a temporary table and re-inserting if there is a simpler solution.
Current script:
alter table the_table add new_field int first;
alter table the_table drop primary key, add primary key (new_field);
alter table the_table change new_field new_field int unsigned not null auto_increment;
I run the script in this order as I can't have an auto-incrementing column that isn't the primary key.
(MySQL 5.3)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试一次性创建列,将其设置为主键并自动递增
Try creating the column, setting it as primary key and auto increment in one go
只需添加一个自增字段,而不是主键:
Just add an auto-increment field, without being a primary key: