【问题标题】:Mysql - Add auto_increment to primary keyMysql - 将 auto_increment 添加到主键
【发布时间】:2011-06-15 06:54:16
【问题描述】:

我有一个奇怪的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,

谢谢!

【问题讨论】:

  • 你能把SHOW CREATE TABLE Parent的结果贴出来

标签: mysql database foreign-keys auto-increment


【解决方案1】:

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

ALTER TABLE Parent MODIFY Identifier smallint(10) AUTO_INCREMENT;

【讨论】:

  • 尝试在运行时禁用foreign_key_checks
  • 设置设置 foreign_key_checks=0;并且运行上面没有任何效果。 :(
  • 缺少无符号数据类型 :)
  • @arnaud576875,奇怪,为什么我们不需要在modify 语句中指定PRIMARY KEY 吗? 为什么在它们的列被修改后键仍然存在?
  • 这根本不起作用!谁有解决方案?
猜你喜欢
  • 1970-01-01
  • 2012-12-05
  • 2015-03-08
  • 1970-01-01
  • 1970-01-01
  • 2020-03-09
  • 1970-01-01
  • 1970-01-01
  • 2018-05-02
相关资源
最近更新 更多