问题描述
数据库中可接受的是圆形引用?
When are circular references acceptable in database?
理论和实用,任何帮助都是值得赞赏的。
Theoretical and practical, any help is appreciated.
推荐答案
指向其他记录的记录在数据库中很有用。有时这些记录形成一个周期。这可能仍然有用。在实践中唯一真正的麻烦是避免违反约束。
Records which point to other records are useful in a database. Sometimes these records form a cycle. This might still be useful. The only real annoyance in practice is avoiding violating the constraints.
例如,如果你有一个用户和事务表,用户可能有一个指向他最后一个事务的指针。您需要先插入事务,然后将 last_transaction_id
更新为正确的值。虽然这两个记录都存在,但不能删除它们,因为 user.last_transaction_id
指向 transaction.id
code> transaction.user_id 指向 user.id
。这意味着没有事务的用户具有null last_transaction_id
。这也意味着你必须null该字段,然后才能删除事务。
For example, if you have a user and transaction table, the user might have a pointer to his last transaction. You need to insert the transaction first, then update the last_transaction_id
to the correct value. While both these records exist you can't erase them, because the user.last_transaction_id
points to transaction.id
and transaction.user_id
points to user.id
. This implies that a user with no transactions has a null last_transaction_id
. It also means that you have to null that field before you can delete the transaction.
管理这些外键约束是一个痛苦,但它当然是可能的。如果您稍后向数据库添加约束引入新的循环依赖性,则可能会出现问题。你必须在这种情况下小心。然而,只要周期中的一个记录具有可空的外键字段,该周期可以被打破并且记录可以被删除。更新通常不是问题,只要您按正确的顺序插入记录。
Managing these foreign key constraints is a pain but it certainly is possible. There may be problems that arise if you add constraints to the database later which introduce new circular dependencies. You have to be careful in this situation. However, as long as one of the records in the cycle has a nullable foreign-key field, the cycle can be broken and the records can be deleted. Updates are not usually a problem as long as you insert the records in the right order.
这篇关于数据库中是否可以接受循环引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!