Derek
Derek

Reputation: 57

mysql - Foreign Key Constraint Fails

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, CONSTRAINT phone_numbers_ibfk_1 FOREIGN KEY (user_id) REFERENCES users (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

Answers (1)

Zaynul Abadin Tuhin
Zaynul Abadin Tuhin

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

Related Questions