Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: How can I change a field that has a foreign key constraint?

I have two tables that are linked by a foreign key constraint. I would like to change an ID field but the following code fails due to the foreign key constraint:

UPDATE A SET id = 1479 WHERE id = 2103;
UPDATE B SET Aid = 1479 WHERE Aid = 2103;

I know I can set up ON CASCADE to do this automatically, but how can I do it on a case-by-case basis like this?

like image 498
David Jones Avatar asked Oct 28 '25 05:10

David Jones


1 Answers

By disabling foreign key checks and by running everything within a transaction.

START TRANSACTION;
SET FOREIGN_KEY_CHECKS = 0;
UPDATE A SET id = 1479 WHERE id = 2103;
UPDATE B SET Aid = 1479 WHERE Aid = 2103;
SET FOREIGN_KEY_CHECKS = 1;
COMMIT;
like image 62
Xandl Avatar answered Oct 31 '25 03:10

Xandl