Mysql - Add auto_increment to primary key(Mysql - 将 auto_increment 添加到主键)
问题描述
我的 mysql 有一个奇怪的问题.
I have a strange problem with mysql.
我正在尝试更改表的列,该列是主键并在其上定义了 auto_increment 约束.这也是多个其他表的外键引用.我需要在父项和所有子项中更改此列的长度.
I am trying to alter a table's column which is a primary key and has an auto_increment constraint defined on it. This is also a foreign key reference for multiple other tables. I need to change the length of this column in both , parent and all children.
set foreign_key_checks=0;
alter table Parent modify Identifier smallint(10) unsigned;
alter table Child_1 modify FK_Identifier smallint(10) unsigned;
alter table Child_2 modify FK_Identifier smallint(10) unsigned;
alter table Child_3 modify FK_Identifier smallint(10) unsigned;
alter table Child_4 modify FK_Identifier smallint(10) unsigned;
alter table Child_5 modify FK_Identifier smallint(10) unsigned;
set foreign_key_checks=1;
这会删除父表上的自动增量.添加约束的最佳方法是什么?
This removes the auto increment on the parent table. What would be the best way to add the constraint back ?
以下似乎失败了.
mysql> ALTER TABLE Parent MODIFY Identifier smallint(10) PRIMARY KEY AUTO_INCREMENT;
ERROR 1068 (42000): Multiple primary key defined
ALTER TABLE Parent MODIFY Identifier smallint(10) AUTO_INCREMENT;
------------------------
LATEST FOREIGN KEY ERROR
------------------------
110125 15:49:08 Error in foreign key constraint of table db/Child_1:
there is no index in referenced table which would contain
the columns as the first columns, or the data types in the
referenced table do not match to the ones in table. Constraint:
,
CONSTRAINT Child_1_ibfk_1 FOREIGN KEY (FK_Identifier) REFERENCES RoomProfile (Identifier) ON DELETE CASCADE ON UPDATE CASCADE
The index in the foreign key in table is PRIMARY
有没有更好的方法来实现这一目标?
Is there a better way to achieve this ?
显示创建是(更改后):
Edit : Show create is (after alter) :
CREATE TABLE `Parent` (
`Identifier` smallint(10) unsigned NOT NULL default '0',
`Name` varchar(20) default NULL,
`Description` varchar(100) default NULL,
PRIMARY KEY (`Identifier`),
UNIQUE KEY `Name` (`Name`),
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
修改前
`Identifier` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
谢谢!
推荐答案
你不需要在MODIFY语句中指定PRIMARY KEY
:
You don't need to specify PRIMARY KEY
in the MODIFY statement:
ALTER TABLE Parent MODIFY Identifier smallint(10) AUTO_INCREMENT;
这篇关于Mysql - 将 auto_increment 添加到主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Mysql - 将 auto_increment 添加到主键


- 更改自动增量起始编号? 2021-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- SQL 临时表问题 2022-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01