在MySQL表中删除外键时如何解决错误?

时间:2019-01-30 21:43:05

标签: mysql foreign-keys

因此,我设法在没有AUTO_INCREMENT的情况下设置了所有主键,如果它也是外键,也无法更改。所以我试图删除外键(然后在之后重新添加它们)。但是它似乎无法识别外键。

mysql> ALTER TABLE Teacher
    -> DROP FOREIGN KEY Credentials_ID;
ERROR 1091 (42000): Can't DROP 'credentials_ID'; check that column/key  exists

mysql> DESCRIBE TEACHER;
+----------------+-------------+------+-----+---------+----------------+  
| Field          | Type        | Null | Key | Default | Extra          |
+----------------+-------------+------+-----+---------+----------------+
| Teacher_ID     | int(11)     | NO   | PRI | NULL    | auto_increment |
| Class_ID       | int(11)     | NO   | MUL | NULL    |                |
| Credentials_ID | int(11)     | NO   | MUL | NULL    |                |
| Teacher_Name   | varchar(20) | YES  |     | NULL    |                |
+----------------+-------------+------+-----+---------+----------------+

如您所见,表中存在Column / Field Credentials_ID。

用于创建表格Teacher的命令:

 mysql> CREATE TABLE Teacher(
     -> Teacher_ID int NOT NULL,
     -> Class_ID int NOT NULL,
     -> Credentials_ID int NOT NULL,
     -> Teacher_Name varchar(20),
     -> PRIMARY KEY (Teacher_ID),
     -> FOREIGN KEY (Class_ID) REFERENCES Class(Class_ID),
     -> FOREIGN KEY (Credentials_ID) REFERENCES Credentials(Credentials_ID)
     -> );

1 个答案:

答案 0 :(得分:1)

DROP FOREIGN KEY的参数是外键的名称,而不是键中列的名称。创建表时,您没有给FK命名,因此MySQL自动分配了一个名称。此默认名称是通过将引用表,被引用表,被引用列名和_fk串联而成的。如果要查看分配的名称,请使用

mysql> SHOW CREATE TABLE Teacher;

结果应包括:

CONSTRAINT `Teacher_Credentials_Credentials_ID_fk` FOREIGN KEY (`Credentials_ID`) REFERENCES `Credentials` (`Credentials_ID`)

要删除FK,您需要提供完整的名称:

mysql> ALTER TABLE Teacher DROP FOREIGN KEY Teacher_Credentials_Credentials_ID_fk;

创建表时,可以为键分配一个较短的名称,以避免出现这些冗长的名称,例如

 mysql> CREATE TABLE Teacher(
     -> Teacher_ID int NOT NULL,
     -> Class_ID int NOT NULL,
     -> Credentials_ID int NOT NULL,
     -> Teacher_Name varchar(20),
     -> PRIMARY KEY (Teacher_ID),
     -> FOREIGN KEY class_ID_fk (Class_ID) REFERENCES Class(Class_ID),
     -> FOREIGN KEY cred_ID_fk (Credentials_ID) REFERENCES Credentials(Credentials_ID)
     -> );

但是,请注意,外键名称在整个数据库中必须是唯一的,因此,您不能有两个带有外键Credentials(Credentials_ID)的表,并且两个表都使用相同的名称cred_ID_fk他们。这就是为什么默认名称在其中包含表名称的原因,它确保您永远不会在这些名称之间发生冲突。