今天在给一个mysql表加外键的时候,总是报错,下面就是报错的SQL语句:
Alter table A
add constraint FK_1 foreign key (`relation_id`) references B(`id`) on update Cascade on delete Cascade
错误代码:1452
看表也没有任何问题,而且relation_id的字段是没有外键的啊~~~
最后在谷歌中查询到一个解决方案,大致的方法如下:
mysql> SET foreign_key_checks = 0; mysql> alter table tblUsedDestination add constraint f_operatorId foreign key(iOperatorId) references tblOperators (iOperatorId); Query OK, 8 rows affected (0.23 sec) Records: 8 Duplicates: 0 Warnings: 0 mysql> SET foreign_key_checks = 1;
先让foreign_key_checks失效,然后再给表加外键,最后再让foreign_key_checks生效!
foreign_key_checks是有原因的。
如果您无法添加外键,因为它违反了约束,您应该首先更正数据。 关闭检查,然后添加键会使您处于不一致的状态。
外键检查增加开销,如果你不想使用它们,那么使用myisam代替