在两个数据库表中进行循环引用是一个好习惯吗

发布于 2024-10-06 09:01:32 字数 181 浏览 4 评论 0原文

在我们的数据库中,我们有两个表 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

伤痕我心 2024-10-13 09:01:32

我认为桥接表非常适合实现两个表之间的多对多关系。并且表之间存在循环引用并不是一个好的做法。

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.

记忆之渊 2024-10-13 09:01:32

考虑以下场景

TableA  TableB
A       1
B       2

如果您想对此进行交叉链接,则至少需要在不创建第三个表的情况下复制两个表之一中的每一行。我怀疑您会发现许多 DBA 愿意为他们的表建立这样的模型。

TableA
A, 1  
A, 2   
B, 1
B, 2

TableB
1
2   

第三张桥牌桌确实是您唯一的好选择。

Consider following scenario

TableA  TableB
A       1
B       2

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.

TableA
A, 1  
A, 2   
B, 1
B, 2

TableB
1
2   

A third bridge table really is your only good option here.

丑丑阿 2024-10-13 09:01:32

这取决于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.

七秒鱼° 2024-10-13 09:01:32

正如 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.

呆° 2024-10-13 09:01:32

您所说的桥接表是连接依赖性的规范化,并且它有良好的理论支持。您不应该在多个位置记录相同的事实。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文