Zakir Bangash
Zakir Bangash

Reputation: 3

How to sovle issue of foreign key constraints fail?

ER_NO_REFERENCED_ROW_2: Cannot add or update a child row: 
a foreign key constraint fails 
(`shahzain`.`branch`, CONSTRAINT `branch_ibfk_1` FOREIGN KEY (`mgr_id`) REFERENCES `employee` (`emp_id`) ON DELETE SET NULL)

This is issue?

Upvotes: 0

Views: 39

Answers (2)

Linda
Linda

Reputation: 88

This usually means there is some flaw in the design of your code. Look at the sequence of insert/updates you are doing.

1.Upsert(Insert or Update) the table employee with newid, name etc of employee

2.Add a row in Branch table, with the information of bank to which this employee is a manager of.

INSERT INTO employee (id, name, dept, age, salary) VALUES (105, 'Srinath', 'Aeronautics', 27, 33000)

INSERT INTO branch (id,  mgr_id, name, branchaddress) VALUES (5, 105, 'Michigan Branch', '1000 MainStreet')

Upvotes: 0

GMB
GMB

Reputation: 222462

The error message is quite clear.

You are trying to insert a row in branch whose mgr_id does not exists in column emp_id of table emp. You have a foreign key constraint that prohibits that.

Either add the missing employee in emp, or attach the branch to another manager, that exists in employee.

Upvotes: 1

Related Questions