MySQL drop table

AL90 picture AL90 · Apr 23, 2012 · Viewed 15.6k times · Source

I want to drop a table with drop table EMPLOYEE;

but I get the error: #1217 - Cannot delete or update a parent row: a foreign key constraint fails

I looked around on the internet to show the hidden constraints and found:

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

After finding this I tried dropping the contraints first with: alter table EMPLOYEE drop contraint 'EMPLOYEE_ibfk_1';

but I keep getting: #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

I have worked at dropping this table for several hours now and searched many topics on the internet. People ended up dropping the db, but I am unauthorized to drop db or create a db.

Answer

ypercubeᵀᴹ picture ypercubeᵀᴹ · Apr 23, 2012

First remove the FOREIGN KEY constraints from DEPARTMENT to EMPLOYEE (note the weird syntax, you should use DROP FOREIGN KEY but with the constraint(!) identifier):

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

Then drop the EMPLOYEE table:

DROP TABLE EMPLOYEE ; 

The problem with your code was that you used DROP CONSTRAINT - which is correct, AFAIK it is the standard SQL syntax for ALTER TABLE.

MySQL however, "prefers" DROP FOREIGN KEY. In other words, it doesn't comply with standards in this case.