简体   繁体   中英

How to delete a foreign key thats references multiple columns in mySQL

I have a foreign key that references two columns in a child table. Id like to delete the foreign key but mySQL just hangs and nothing happens:

Here is the output from SHOW CREATE TABLE table_name :

KEY FK_animal_index (animal_type,food_index), CONSTRAINT FK_animal_index FOREIGN KEY (animal_type, food_index) REFERENCES animal_schedules (animal_type, food_index) ENGINE=InnoDB

I have tried deleting this foreign key using:

`ALTER TABLE table_name DROP FOREIGN KEY FK_animal_index;`

`ALTER TABLE table_name DROP FOREIGN KEY animal_type;`

ALTER TABLE section_configuration DROP FOREIGN KEY FK_animal_index, DROP KEY (animal_type, food_index);

AND

ALTER TABLE section_configuration DROP FOREIGN KEY FK_animal_index , ADD CONSTRAINT FK_animal_type FOREIGN KEY (animal_type) REFERENCES animal_schedules ( animal_type ) ON DELETE SET NULL;

Others have mentioned that ON DELETE not being set can prevent you changing key values (mySQL will reject the change if ON DELETE is not set to anything)

But to no avail, mySQL just hangs and 30 minutes later still nothing. The database is very small at the moment so removing the FK should be fast.

The answer to this question was not about primary keys at all. I had to stop my program from accessing the table in order to make modifications to it. In mySQL db, you can add tables and add columns at any time, but if you want to change a column or remove a column, it must not be in use by any program or it will hang indefinitely.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM