Mysql - 将自动增量添加到主键

时间:2011-01-25 15:33:53

标签: mysql database foreign-keys auto-increment

我对mysql有一个奇怪的问题。

我正在尝试更改表的列,该列是主键并且在其上定义了auto_increment约束。这也是多个其他表的外键引用。 我需要在父级和所有子级中更改此列的长度。

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;

这将删除父表上的自动增量。什么是添加约束的最佳方法?

以下似乎失败了。

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

有没有更好的方法来实现这一目标?

编辑:显示创建是(更改后):

  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,

谢谢!

1 个答案:

答案 0 :(得分:37)

您无需在MODIFY语句中指定PRIMARY KEY

ALTER TABLE Parent MODIFY Identifier smallint(10) AUTO_INCREMENT;