CREATE OR REPLACE TEMPORARY TABLE tItemShelving (PRIMARY KEY (id)) ENGINE = MEMORY SELECT ish.id, s.id shelvingFk FROM shelving s JOIN itemShelving ish ON ish.shelvingFk = s.code; ALTER TABLE vn.itemShelving DROP FOREIGN KEY itemShelving_fk2, MODIFY COLUMN shelvingFk int(11) NOT NULL; UPDATE itemShelving ish JOIN tItemShelving tis ON tis.id = ish.id SET ish.shelvingFk = tis.shelvingFk; DROP TEMPORARY TABLE tItemShelving; ALTER TABLE vn.itemShelving ADD CONSTRAINT itemShelving_shelving_FK FOREIGN KEY (shelvingFk) REFERENCES vn.shelving(id) ON DELETE RESTRICT ON UPDATE CASCADE;