How to delete a record when two tables have a foreign key referenced by each other?

Delete any entry from them, report the error as follows:

ERROR 1451 (23000): Cannot delete or update parent row: foreign key constraint does not work

How to solve this problem?

+4
source share
5 answers

Select a record that allows you to insert null in the FK column, insert there, delete another record, and then delete the first.

+5
source

or

 ON DELETE CASCADE 

or insert NULL for one of the FK, if possible in your scheme, cannot provide more information without knowing the seller.

+4
source

if your column is AllowNull, update its data to zero, and then delete the data.

+1
source

If both tables reference a foreign key to each other, it is very likely that the database design needs to be improved. I think this should call an extra table to take care of this design.

For your question, you can update the FK key field in one table to zero, and then start the deletion in both tables.

But in order for this to happen, make sure that you have identified PK in advance to remove them.

Kalpak

0
source
 ALTER TABLE <table1> NOCHECK CONSTRAINT ALL GO ALTER TABLE <table2> NOCHECK CONSTRAINT ALL GO DELETE FROM <table1> GO DELETE FROM <table2> GO ALTER TABLE <table1> CHECK CONSTRAINT ALL GO ALTER TABLE <table2> CHECK CONSTRAINT ALL GO 
0
source

Source: https://habr.com/ru/post/1302580/


All Articles