4

我想删除一张桌子drop table EMPLOYEE;

但我得到了错误:#1217 - Cannot delete or update a parent row: a foreign key constraint fails

我在互联网上环顾四周以显示隐藏的约束并发现:

CREATE TABLE `EMPLOYEE` (
`Ssn` int(9) NOT NULL,
`Dno` int(11) NOT NULL,
UNIQUE KEY`Ssn_8` (`Ssn`),
UNIQUE KEY`Dno_13` (`Dno`),
CONSTRAINT `EMPLOYEE_ibfk_1` FOREIGN KEY(`Dno`) REFERENCES `DEPARTMENT` (`Dnumber`),
CONSTRAINT `EMPLOYEE_ibfk_2` FOREIGN KEY(`Dno`) REFERENCES `DEPARTMENT` (`Dnumber`),
CONSTRAINT `EMPLOYEE_ibfk_3` FOREIGN KEY(`Dno`) REFERENCES `EMPLOYEE` (`Dno`),
CONSTRAINT `EMPLOYEE_ibfk_4` FOREIGN KEY(`Dno`) REFERENCES `EMPLOYEE` (`Dno`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1




   CREATE TABLE `DEPARTMENT` (
`Dnumber` int(11) NOT NULL,
`Mgr_ssn` int(9) NOT NULL,
UNIQUE KEY`Mgr_ssn` (`Mgr_ssn`),
UNIQUE KEY`Dnumber` (`Dnumber`),
CONSTRAINT `DEPARTMENT_ibfk_1` FOREIGN KEY(`Mgr_ssn`) REFERENCES `EMPLOYEE` (`Ssn`),
CONSTRAINT `DEPARTMENT_ibfk_2` FOREIGN KEY(`Mgr_ssn`) REFERENCES `EMPLOYEE` (`Ssn`),
CONSTRAINT `DEPARTMENT_ibfk_3` FOREIGN KEY(`Mgr_ssn`) REFERENCES `DEPARTMENT` (`Mgr_ssn`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

找到这个后,我尝试首先删除约束: alter table EMPLOYEE drop contraint 'EMPLOYEE_ibfk_1';

但我不断得到: #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''EMPLOYEE_ibfk_1'' at line 1

我已经在删除这张表上工作了几个小时,并在互联网上搜索了许多主题。人们最终放弃了数据库,但我无权删除数据库或创建数据库。

4

3 回答 3

9

首先从to中删除FOREIGN KEY约束(注意奇怪的语法,你应该使用但是带有约束(!)标识符):DEPARTMENTEMPLOYEEDROP FOREIGN KEY

ALTER TABLE DEPARTMENT
  DROP  FOREIGN KEY  DEPARTMENT_ibfk_1 ,
  DROP  FOREIGN KEY  DEPARTMENT_ibfk_2 ;

然后删除EMPLOYEE表:

DROP TABLE EMPLOYEE ; 

您的代码的问题在于您使用了DROP CONSTRAINT- 这是正确的,AFAIK 它是ALTER TABLE.

然而,MySQL “更喜欢” DROP FOREIGN KEY. 换句话说,在这种情况下它不符合标准。

于 2012-04-22T22:58:28.983 回答
1

外键名称需要用反引号引起来:

alter table EMPLOYEE drop constraint `EMPLOYEE_ibfk_1`;
                                     ^               ^

使用'单引号将其变成一个字符串。

于 2012-04-22T22:12:48.570 回答
0

您需要删除表 Employee 中的外键以及 Department 表中的外键,然后尝试删除它。

注意:需要删除部门表中首先引用的表的外键。

还要首先删除 Department 表中对 Employee 的任何引用。

于 2012-04-22T22:08:19.547 回答