简体   繁体   中英

Delete from two tables with circular foreign keys

I have two tables

TableOne (TABLE_ONE_ID (pk), TABLE_TWO_ID (fk), ...(something else) )
TableTwo (TABLE_TWO_ID (pk), TABLE_ONE_ID (fk), ...(something else) )

How can I delete records from these tables?

PS I think that it is bad design, but this is not my fault and I don't have permission to change the database structure. I just need to know how to delete records from these tables.

I'm not sure of the best way to go about this but I would probably do something like:

UPDATE TableOne SET TABLE_TWO_ID = null;
DELETE FROM TableTwo;
DELETE FROM TableOne;

Either defer one of the foreign keys, or assign NULL (assuming it is NULL-able) to break the cycle.

BTW, how are you inserting the data? You must have done something to break the cycle there too.

NOTE: Disabling or deleting the FK may be OK if just one carefully controlled session is modifying the database, but would leave you wide open for data corruption in a concurrent environment where other clients may not be aware that the FK they expect is no longer enforced.

You can disable the foreign key with:

alter table TableOne disable constraint fk_table_two_id;

After that, you should be able to delete the rows.

Per DaveCosta's comment, you could defer the constraint checks. That way the constraints are checked over the entire transaction, not each individual SQL statement. For example:

begin transaction;
set constraints all deferred; 
delete from TableTwo;
delete from TableOne;
commit transaction;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM