从具有圆形外键的两个表中删除

[英]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?

如何从这些表中删除记录?

P.S. 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.

附:我认为这是糟糕的设计,但这不是我的错,我没有权限更改数据库结构。我只需要知道如何从这些表中删除记录。

3 个解决方案

#1


14  

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;

#2


6  

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

延迟其中一个外键,或者指定NULL(假设它是NULL可以)来打破循环。

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.

注意:如果只有一个精心控制的会话正在修改数据库,则禁用或删除FK可能没问题,但是在并发环境中,如果其他客户端可能不知道他们不再强制执行他们期望的FK,那么会让您彻底打开数据损坏。

#3


3  

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:

根据DaveCosta的评论,您可以推迟约束检查。这样就可以在整个事务中检查约束,而不是每个单独的SQL语句。例如:

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

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2012/08/31/fd8f5e9bc8ec06db4cf8c8547a393863.html



 
© 2014-2018 ITdaan.com 粤ICP备14056181号