mySQL How to alter column to have foreign key?

10,821

Just use ALTER TABLE along with ADD CONSTRAINT:

ALTER TABLE `table` ADD CONSTRAINT fk_l_id FOREIGN KEY (id_l) REFERENCES table_b(id_l);
Share:
10,821
slipperyiron
Author by

slipperyiron

Updated on June 04, 2022

Comments

  • slipperyiron
    slipperyiron almost 2 years

    I want to alter a column in one of my tables to that it references another column in another table. I've tried to introduce a foreign key the following ways:

    ALTER TABLE `table` ALTER COLUMN `id_l` int NOT NULL, foreign key (`id_l`) references table_b(`id_l`);

    ALTER TABLE `table` CHANGE `id_l` `id_l` int NOT NULL, foreign key (`id_l`) references table_b(`id_l`);

    I am thrown a syntax error.

    A work around is to delete the table and create a new one with the desired reference (this works) but I want to change this table as it is, not to transfer the data. How do I do this?

    MySQL Server 5.6.17