Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Removing Some Foreign keys

I have a table whose primary key is used in several other tables and has several foreign keys to other tables.

CREATE TABLE location (    locationID INT NOT NULL AUTO_INCREMENT PRIMARY KEY    ... ) ENGINE = InnoDB;  CREATE TABLE assignment (    assignmentID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,    locationID INT NOT NULL,    FOREIGN KEY locationIDX (locationID) REFERENCES location (locationID)    ... ) ENGINE = InnoDB;  CREATE TABLE assignmentStuff (    ...    assignmentID INT NOT NULL,    FOREIGN KEY assignmentIDX (assignmentID) REFERENCES assignment (assignmentID) ) ENGINE = InnoDB; 

The problem is that when I'm trying to drop one of the foreign key columns (ie locationIDX) it gives me an error.

"ERROR 1025 (HY000): Error on rename"

How can I drop the column in the assignment table above without getting this error?

like image 894
Drew Avatar asked May 08 '09 05:05

Drew


People also ask

How do I delete a foreign key in MySQL?

Dropping Foreign Key Constraints You can drop a foreign key constraint using the following ALTER TABLE syntax: ALTER TABLE tbl_name DROP FOREIGN KEY fk_symbol; If the FOREIGN KEY clause defined a CONSTRAINT name when you created the constraint, you can refer to that name to drop the foreign key constraint.

How do I remove a foreign key constraint in MySQL workbench?

To drop a foreign key, right-click the row you wish to delete, then select the Delete Selected FKs menu item. To modify properties of a foreign key, select it and make the desired changes.

How do I drop a key in MySQL?

To drop a non-primary key index, use the DROP INDEX command: DROP INDEX index_name ON table_name; The syntax requires the table name to be specified because MySQL allows index names to be reused on multiple tables.


2 Answers

As explained here, seems the foreign key constraint has to be dropped by constraint name and not the index name.

The syntax is:

ALTER TABLE footable DROP FOREIGN KEY fooconstraint; 
like image 98
pugmarx Avatar answered Sep 21 '22 22:09

pugmarx


The foreign keys are there to ensure data integrity, so you can't drop a column as long as it's part of a foreign key. You need to drop the key first.

I would think the following query would do it:

ALTER TABLE assignmentStuff DROP FOREIGN KEY assignmentIDX; 
like image 30
zombat Avatar answered Sep 20 '22 22:09

zombat