在两个数据库表中进行循环引用是一个好习惯吗
在我们的数据库中,我们有两个表 A、B,主键为 A_id 和 B_id。
将 B_id 作为表 A 中的外键,将 A_id 作为表 B 中的外键是否被认为是一个好的做法。这将允许我们在表中拥有多对多关系。
另一种方法是使用仅包含 A_id 和 B_id 两列的第三个桥接表。
您认为哪一个是好的做法?
In our DB we have two tables A, B with primary keys A_id and B_id.
Is it a considered a good practice to have B_id as foreign key in table A and A_id as foreign key in table B. This would allow us to have many-to-many relationship in the table.
An alternative would be to have a third bridge table consisting of just two columns A_id and B_id.
Which one do you think is a good practice?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我认为桥接表非常适合实现两个表之间的多对多关系。并且表之间存在循环引用并不是一个好的做法。
I think a bridge table would be ideal for implementing many to many relationship between two tables.And it is not a good practice to have a circular reference between tables.
考虑以下场景
如果您想对此进行交叉链接,则至少需要在不创建第三个表的情况下复制两个表之一中的每一行。我怀疑您会发现许多 DBA 愿意为他们的表建立这样的模型。
第三张桥牌桌确实是您唯一的好选择。
Consider following scenario
If you want to crosslink this, the least you need to do without creating a third table is duplicating every row in one of the two tables. I doubt you'll find many DBA's willing to model their tables like that.
A third bridge table really is your only good option here.
这取决于A和B之间的关系,是一对一、一对多还是多对多。但总的来说,循环引用是不好的,因为它们增加了保持两个表同步所需的维护量。
It depends on the relationship between A and B, whether it is one-to-one, one-to-many, or many-to-many. In general, though, circular references are bad simply because they increase the amount of maintenance you have to do to keep the two tables in sync.
正如 wizzardz 提到的,尤其是 DBMS,我会尽量避免循环引用。
它有可能给您带来很多问题。此外,如果其他人将使用该设计,您将必须确定其文档,因为他们最终可能会绕圈子试图解决它。
As wizzardz mentioned and espically with DBMSs, i'd try to avoid circular references.
It has the potential of causing you a great deal of problems. Also if others will be working with that design, you'll have to nail down the documentation for it as they could end up going round in circles trying to work it out.
您所说的桥接表是连接依赖性的规范化,并且它有良好的理论支持。您不应该在多个位置记录相同的事实。
What you call a bridge table is the normalization of a join dependency, and it's supported by good theory. You should not be recording the same fact in multiple locations.