Reputation: 57
Hi I know this has been asked but I haven't found the correct answer, how come when I try to do my second insert:
INSERT INTO phone_numbers (phone_number) VALUES ('226');
I get the error:
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (
week7
.phone_numbers
, CONSTRAINTphone_numbers_ibfk_1
FOREIGN KEY (user_id
) REFERENCESusers
(id
))
DDL CODE BELOW:
create table users (
id int unsigned not null auto_increment,
name varchar(100) not null,
primary key(id)
);
INSERT INTO users (name) VALUES ('alex');
create table phone_numbers (
id int unsigned not null auto_increment,
user_id int unsigned not null,
phone_number varchar(25) not null,
primary key(id),
foreign key (user_id) references users (id)
);
INSERT INTO phone_numbers (phone_number) VALUES ('226');
Upvotes: 0
Views: 64
Reputation: 32001
as in your user_id field does not have defalult value that's why it thrown error use like below your insert will work
INSERT INTO phone_numbers (user_id,phone_number) VALUES (1,'226');
Upvotes: 1