如何将现有 MySQL 表中的数据更改为从最后一个最高 id 自动增量?
我刚刚成功将一个相当大的数据库从 SQL Server 迁移到 MySQL。我没有在迁移过程中将主键设置为自动增量,因为这些表具有基于 ids 作为主键的关系,而 id 是另一个表中的外键。
现在,为了添加新记录,我想将所有表中的主键“id”列更改为自动增量,但从每个表中 id 列中的最后一个最高数字开始。
在不失去已有关系的情况下做到这一点的最佳方法是什么?
更新:尝试添加自动增量给了我这个错误:
ERROR 1067: Invalid default value for 'id'
SQL Statement:
ALTER TABLE `skandium`.`brands` CHANGE COLUMN `id` `id` INT(11) NOT NULL DEFAULT '0' AUTO_INCREMENT
ERROR 1050: Table 'brands' already exists
SQL Statement:
CREATE TABLE `brands` (
`id` int(11) NOT NULL DEFAULT '0',
`brand` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
I have just managed to migrate a pretty big database from SQL Server to MySQL. I didn't set the primary keys to auto increment during the migration because the tables have relationships based on ids as primary keys which are foreign keys in another table.
Now for adding new records I want to alter the primary key 'id' columns in all tables to be autoincrement but starting from the last highest number in the id column in each table.
What's the best way to do this without losing the relationships I already have?
UPDATE: Trying to add autoincrement gives me this error:
ERROR 1067: Invalid default value for 'id'
SQL Statement:
ALTER TABLE `skandium`.`brands` CHANGE COLUMN `id` `id` INT(11) NOT NULL DEFAULT '0' AUTO_INCREMENT
ERROR 1050: Table 'brands' already exists
SQL Statement:
CREATE TABLE `brands` (
`id` int(11) NOT NULL DEFAULT '0',
`brand` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需在您需要的列上添加自动增量即可。它不会影响现有行。它将从下一个可用值开始。
请注意,自动递增的列意味着如果您不为其分配值,MySQL 将添加一个值。如果您想提供明确的值,您可以这样做,而不会发生任何特殊情况。因此,您可以从一开始就将这些列设置为自动递增。
具有自动增量的列不能具有显式默认值。
已测试
Just add the auto-increment on your needed columns. It won't affect existing rows. It will start with the next available value.
Note that a column being auto-increment means just that if you don't assign a value to it one will be added by MySQL. If you want to supply explicit values you can do so without anything special happening. So you could have set those columns to auto-increment right from the start.
A column with auto-increment cannot have an explicit default value.
Tested