Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails for existing tables

I am getting following error while assigning foreign key to existing table column:

ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (c_x_parsing.#sql-787_1, CONSTRAINT #sql-787_1_ibfk_1 FOREIGN KEY (nct_id) REFERENCES cdb (nct_id))

Below is the my query:

ALTER TABLE c_int ADD FOREIGN KEY (n_id) REFERENCES cdb (n_id);

While my parent table is cdb cdb and child table is c_int.

Please suggest me the solution as I already tried with following commands:

ALTER TABLE cdb ENGINE=InnoDB;
ALTER TABLE c_int ENGINE=InnoDB;
like image 703
user2818537 Avatar asked Oct 08 '13 07:10

user2818537


People also ask

How do I fix error code 1452 in MySQL?

Disable the FOREIGN_KEY_CHECKS variable in MySQL server. — set for the current session: SET FOREIGN_KEY_CHECKS=0; — set globally: SET GLOBAL FOREIGN_KEY_CHECKS=0; Now we can INSERT or UPDATE rows in our table without triggering a foreign key constraint fails.

How do I fix foreign key constraint failure?

The error message itself showing there is a foreign key constraint error, which means you are deleting a parent table where the child table contains the Primary table identifier as a foreign key. To avoid this error, you need to delete child table records first and after that the parent table record.

How do you solve this error Cannot add or update a child row a foreign key constraint fails?

You are getting this constraint check because Ordre table does not have reference OrdreID provided in insert command. To insert value in Ordrelinje, you first have to enter value in Ordre table and use same OrdreID in Orderlinje table. Or you can remove not null constraint and insert a NULL value in it. Hope it helps!!

How do you fix Integrity constraint violation 1452 Cannot add or update a child row a foreign key constraint fails?

If you are getting error Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails while using php artisan migrate command after creating a migration file. You can set foreign id column value as nullable with null on delete on delete parent table record.


1 Answers

The issue is not the command, but the data. There's a value in the child table that does not exist in the parent table.

Try using something like this to figure out which data is causing the issue:

SELECT n_id FROM c_int WHERE n_id NOT IN (SELECT n_id FROM cdb)
like image 89
SchmitzIT Avatar answered Oct 19 '22 19:10

SchmitzIT