MySQL删除foreign key_ERROR 1025 ,HY000: Error on rename of './test_20180206/cc' to './test_20180206/#sql2-9ac-e'

问题背景描述:

首先,创建了一个主表,具有以下数据结构:

mysql> describe aa;
+-------+----------+------+-----+---------+----------------+
| Field | Type     | Null | Key | Default | Extra          |
+-------+----------+------+-----+---------+----------------+
| ID    | int(11)  | NO   | PRI | NULL    | auto_increment |
| SecID | int(10)  | NO   | UNI | NULL    |                |
| name  | char(20) | NO   |     | NULL    |                |
| sex   | char(5)  | YES  |     | femal   |                |
+-------+----------+------+-----+---------+----------------+
4 rows in set (0.01 sec)

然后,创建了一个从表,通过外键,与表aa的SecID属性关联起来:

mysql> create table bb  //创建表bb
    -> (SecID int(10) unique not null,
    -> room_num int(5) not null,
    -> extra binary default 0)
    -> engine=InnoDB;
Query OK, 0 rows affected (0.10 sec)
mysql> alter table bb add foreign key(SecID) references aa(SecID); //添加外键
Query OK, 0 rows affected (0.14 sec)
Records: 0  Duplicates: 0  Warnings: 0

执行对bb表的外键删除操作,出现以下error:

mysql> alter table cc drop foreign key SecID;
ERROR 1025 (HY000): Error on rename of './test_20180206/cc' to './test_20180206/#sql2-9ac-e' (errno: 152)

经过分析,笔者发现是因为创建外键时,外键名与属性名一样导致的。

因此,在创建外键时,最好加上外键的别名设置,以便于外键属性的修改或删除,命令如下:

mysql> alter table cc add constraint SECID foreign key(SecID) references aa(SecID);
mysql> alter table cc drop foreign key SECID;
Query OK, 0 rows affected (0.16 sec)
Records: 0  Duplicates: 0  Warnings: 0

目前没有找到外键名与属性名一致时,删除外键的彻底解决方法。

可以通过命令CREATE TABLE SELECT的命令将表结构及其数据进行备份,此时外键属性是不会被复制的,就可以根据新表重新进行可靠的外键设置操作。