删除表上的外键约束出错

时间:2013-05-31 12:36:28

标签: mysql database foreign-keys drop-table table-rename

执行以下SQL命令时:

CREATE TABLE `TableA` (
  `tableAId` INT(11) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`tableAId`)
);

CREATE TABLE `TableB` (
  `tableBId` INT(11) NOT NULL AUTO_INCREMENT,
  `tableAId` INT(11) DEFAULT NULL,
  PRIMARY KEY (`tableBId`),
  CONSTRAINT `FK_TABLE_A_ID` FOREIGN KEY (`tableAId`) REFERENCES `TableA` (`tableAId`)
);

ALTER TABLE `TableB`
    RENAME TO `NewTableB`;

ALTER TABLE `TableA`
    RENAME TO `NewTableA`,
    CHANGE COLUMN `tableAId` `newTableAId` INT(11) NOT NULL AUTO_INCREMENT FIRST;

DROP TABLE IF EXISTS NewTableA;

DROP TABLE IF EXISTS NewTableB;

CREATE TABLE `TableA` (
  `tableAId` INT(11) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`tableAId`)
);

我在最后一个命令(即CREATE TABLE TableA (...))上有以下错误:

  

Erreur SQL(1005):无法创建表'TableA'(错误号:150)外来   键约束形成错误

当我执行show engine innodb status时,我有:

------------------------
LATEST FOREIGN KEY ERROR
------------------------
130531 12:06:05 Error in foreign key constraint of table TableB:
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 the ones in table. Constraint:
,
  CONSTRAINT `FK_TABLE_A_ID` FOREIGN KEY (`tableAId`) REFERENCES `NewTableA` (`tableAId`)

1 个答案:

答案 0 :(得分:0)

老问题,但对于处于类似情况的其他人,我的答案是:

https://dba.stackexchange.com/a/87587/56052

可能会有所帮助。

  • 使用与之前相同的外键规范重新创建表,但是a 不同的名字。
  • 删除生成的表(也将丢弃原始的孤立外键)
  • 使用原始密钥或无外键重新创建表