I tried to simplify the problem so we can focus on the main problem.
I think the main problem is that when we add a foreign key constrant, we have to know which row in the foreign table we refer to.
I previously added a primary key but that is not necessary.
All we need to do is ensure that the id in the parent_table is unique.
create table child_table (`id` int(10) not null);
create table parent_table (id int(5) not null, second_column varchar(20));
alter table child_table add column parent_id int(5);
insert into parent_table values (1, "first");
insert into parent_table values (2, "second");
insert into child_table values (1, null);
ALTER TABLE child_table
ADD CONSTRAINT fk_parent_id
FOREIGN KEY (parent_id)
REFERENCES parent_table(id);
and I am able to reproduce the problem http://www.sqlfiddle.com/#!9/9f6286
and we can solve this by making the id in parent_table a primary key
create table child_table
(`id` int(10) not null);
create table parent_table
(id int(5) not null primary key,
second_column varchar(20));
alter table child_table
add column parent_id int(5);
insert into parent_table values (1, "first");
insert into parent_table values (2, "second");
insert into child_table values (1, null);
ALTER TABLE child_table
ADD CONSTRAINT fk_parent_id
FOREIGN KEY (parent_id)
REFERENCES parent_table(id);
You can also declare the ID in the parent_table as unique. That will work as well.
create table child_table
(`id` int(10) not null);
create table parent_table
(id int(5) not null unique,
second_column varchar(20));
alter table child_table
add column parent_id int(5);
insert into parent_table values (1, "first");
insert into parent_table values (2, "second");
insert into child_table values (1, null);
ALTER TABLE child_table
ADD CONSTRAINT fk_parent_id
FOREIGN KEY (parent_id)
REFERENCES parent_table(id);