Create related tables during a schema migration¶
In an isolated session, temporarily disable foreign-key checks to create the child definition before its parent, then re-enable checks before loading rows. Never leave the setting disabled for application traffic.
CREATE DATABASE cookbook_fk;
USE cookbook_fk;
SET FOREIGN_KEY_CHECKS=0;
CREATE TABLE child(id INT PRIMARY KEY, parent_id INT,
CONSTRAINT fk_parent FOREIGN KEY(parent_id) REFERENCES parent(id));
CREATE TABLE parent(id INT PRIMARY KEY);
SET FOREIGN_KEY_CHECKS=1;
INSERT INTO parent VALUES(1);
INSERT INTO child VALUES(1,1);
SELECT c.id,p.id AS parent_id FROM child c JOIN parent p ON c.parent_id=p.id;
SHOW CREATE TABLE child;
DROP DATABASE cookbook_fk;
The join returns child 1 with parent 1, and SHOW CREATE TABLE includes the foreign key. Re-enabling checks does not retroactively validate any rows inserted while checks were off; load data only after re-enabling. See the v4.2.4 source test.