How to add Foreign Key (MySQL)

纵饮孤独 提交于 2019-11-30 05:43:43

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!