删除外键后,mySQL 表中的键值 MUL 没有变化

问题描述

student table:
+---------------+----------+------+-----+---------+-------+
| Field         | Type     | Null | Key | Default | Extra |
+---------------+----------+------+-----+---------+-------+
| stu_id        | int      | NO   | PRI | NULL    |       |
| stu_name      | char(30) | YES  | UNI | NULL    |       |
| stu_branch_id | int      | NO   | MUL | NULL    |       |
+---------------+----------+------+-----+---------+-------+

branch table:
+--------------------+----------+------+-----+---------+-------+
| Field              | Type     | Null | Key | Default | Extra |
+--------------------+----------+------+-----+---------+-------+
| branch_id          | int      | NO   | PRI | NULL    |       |
| branch_name        | char(30) | YES  | UNI | NULL    |       |
| branch_building_no | int      | YES  |     | NULL    |       |
+--------------------+----------+------+-----+---------+-------+

MysqL> alter table student add constraint fk_student foreign key (stu_branch_id) references branch(branch_id);
Query OK,5 rows affected (2.69 sec)
Records: 5  Duplicates: 0  Warnings: 0

desc student;
+---------------+----------+------+-----+---------+-------+
| Field         | Type     | Null | Key | Default | Extra |
+---------------+----------+------+-----+---------+-------+
| stu_id        | int      | NO   | PRI | NULL    |       |
| stu_name      | char(30) | NO   |     | NULL    |       |
| stu_branch_id | int      | NO   | MUL | NULL    |       |
+---------------+----------+------+-----+---------+-------+
3 rows in set (0.00 sec)

MysqL> alter table student 
    -> drop foreign key fk_student;
Query OK,0 rows affected (0.21 sec)
Records: 0  Duplicates: 0  Warnings: 0

MysqL> desc student;
+---------------+----------+------+-----+---------+-------+
| Field         | Type     | Null | Key | Default | Extra |
+---------------+----------+------+-----+---------+-------+
| stu_id        | int      | NO   | PRI | NULL    |       |
| stu_name      | char(30) | YES  | UNI | NULL    |       |
| stu_branch_id | int      | NO   | MUL | NULL    |       |
+---------------+----------+------+-----+---------+-------+
3 rows in set (0.01 sec)



MysqL> alter table student 
    -> add constraint fk_student foreign key (stu_id_branch) references branch(branch_id) on delete cascade;
ERROR 1061 (42000): Duplicate key name 'fk_student'

删除外键后,MUL 键还在。 现在,当我尝试添加一个具有相同名称的外键时,出现错误

解决方法

隐式索引创建导致的问题。创建外键 fk_student 时,索引 fk_student 也创建了。如果您需要回滚 FK 创建,您需要下一步:

alter table student drop foreign key fk_student,drop key fk_student;

SQL fiddle here