How to add Foreign Key (MySQL)

You can’t add a NOT NULL column to a table that has more than zero rows, when the column is constrained to values that match those in the parent table, and yet has only NULL values because it’s a new, unpopulated column with no DEFAULT.

The workaround is to do it in stages: add the column, but don’t declare it NOT NULL, and don’t declare the foreign key yet.

ALTER TABLE boys
 ADD COLUMN toy_id INT;

Then populate it with valid data that matches some value(s) in your toys table.

UPDATE boys SET toy_id = ...;

Then alter the column to be NOT NULL, and create the constraint:

ALTER TABLE boys MODIFY COLUMN toy_id INT NOT NULL,
 ADD CONSTRAINT toys_toy_id_fk
 FOREIGN KEY(toy_id)
 REFERENCES toys(toy_id);

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)