How to alter a MySQL table's foreign key using the command line

el ninho picture el ninho · Jun 17, 2012 · Viewed 38.7k times · Source

How to alter an existing table in MySQL, setting foreign key to another table, using the command line?

Answer

WojtekT picture WojtekT · Jun 17, 2012

You have to drop existing foreign key and create another one. For example like this:

ALTER TABLE my_table DROP FOREIGN KEY my_key;
ALTER TABLE my_table ADD CONSTRAINT my_key FOREIGN KEY ('some_id') 
REFERENCES some_new_table ('some_other_id') ON UPDATE CASCADE ON DELETE CASCADE;