如何删除不存在的外键约束?

时间:2016-01-24 03:59:17

标签: mysql foreign-keys

我在尝试将我的PSA_Landing.tblSubsDetails SubmissionID字段(目前是PK)更改为自动增量字段以便对某些不相关的内容进行快速测试的过程中遇到了这个问题。

尝试运行时:

ALTER TABLE `PSA_Landing`.`tblSubsDetails` CHANGE COLUMN `SubmissionID`
`SubmissionID` INT(11) NOT NULL AUTO_INCREMENT ;

我收到错误:

ERROR 1833: Cannot change column 'SubmissionID': used in a foreign key 
constraint 'fk_StatusSubmissionId' of table 'PSA_Landing.tblSubsStatus'

问题是......我没有表PSA_Landing.tblSubsStatus ...我将其重命名为PSA_Landing.tblSubmissionStatus。它上面也没有FK。

当试图将tblSubmissionStatus改回到tblSubsStatus(只是为了看它是否有帮助)时,我得到一个错误1025:

 Apply changes to tblSubsStatus Error 1025: Error on rename of
'./PSA_Landing/tblSubmissionStatus' to './PSA_Landing/tblSubsStatus' (errno: 
150 - Foreign key constraint is incorrectly formed) SQL Statement: ALTER 
TABLE `PSA_Landing`.`tblSubmissionStatus`  RENAME TO `PSA_Landing`.`tblSubsStatus`

然后我跑了:

SHOW ENGINE innodb STATUS

找到这个:

 ------------------------
LATEST FOREIGN KEY ERROR
------------------------
2016-01-24 03:15:32 7fc4410fb700 Error in foreign key constraint of table PSA_Landing/tblSubsStatus:
there is no index in the table which would contain
the columns as the first columns, or the data types in the
table do not match the ones in the referenced table
or one of the ON ... SET NULL columns is declared NOT NULL. Constraint:
,
CONSTRAINT "fk_StatusSubmissionId" FOREIGN KEY ("fk_SubmissionId") REFERENCES "tblSubsDetails" ("SubmissionID") ON DELETE NO ACTION ON UPDATE NO ACTION

最后这引导我尝试:

alter table PSA_Landing.tblSubsStatus
drop foreign key fk_StatusSubmissionID

预计会给出:

alter table PSA_Landing.tblSubsStatus  drop foreign key fk_StatusSubmissionID      
Error Code: 1146. Table 'PSA_Landing.tblSubsStatus' doesn't exist

出于绝望,我试了这个:

alter table PSA_Landing.tblSubmissionStatus
drop foreign key fk_StatusSubmissionID

哪个收益率:

Error Code: 1091. Can't DROP 'fk_StatusSubmissionID'; check that column/key exists  

所以简而言之......

当该表不存在时,如何从表PSA_Landing.tblSubsStatus中删除约束fk_StatusSubmissionId?

1 个答案:

答案 0 :(得分:0)

SET @@FOREIGN_KEY_CHECKS = 0;导致InnoDB禁用对DML的参照完整性检查,并允许某些与外键相关的无效DDL操作,例如创建一个引用表的外键约束的表还没有存在,或者丢弃外键引用的表,同时仍然禁止公开无效的请求,例如REFERENCES引用具有不匹配数据类型的列或格式错误的外键定义。

此语句在会话级别运行,因此它不会禁用整个服务器的外键约束。它通常仅在从备份恢复的过程中使用(语句由mysqldump注入转储文件并在重新加载操作期间定期执行)并且在操作上是必要的,因为它并不总是可以解析循环外键中的依赖项(mysqldump没有看到 - 表格按词汇顺序转储。)

在这种情况下,解决方案是重新创建然后删除幻像引用表,同时禁用FOREIGN_KEY_CHECKS

http://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html#sysvar_foreign_key_checks