如何在 PostgreSQL 中建立这种关系?

发布于 2024-10-20 12:37:31 字数 285 浏览 4 评论 0原文

多对多整体参与关系(双向)

您好。

如 ER 模型所示,我想在“Busses”和“Chauffeurs”之间创建一种关系,其中“Chauffeurs”中的每个实体必须在“Certified”中至少有一个关系,并且“Busses”中的每个实体必须在“已认证”中至少有一种关系。

虽然设计 ER 模型非常容易,但我似乎找不到在 PostgreSQL 中建立这种关系的方法。有人有一些想法吗?

谢谢

A many-to-many toal participation relation (both ways)

Hello.

As shown in the ER model, I want to create a relation between "Busses" and "Chauffeurs", where every entity in "Chauffeurs" must have at least one relation in "Certified", and every entity in "Busses" must have at least one relation in "Certified".

Though it was pretty easy to design the ER model, I can't seem to find a way of making this relation in PostgreSQL. Anybody got some ideas ?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

撧情箌佬 2024-10-27 12:37:31

该解决方案应该与数据库无关。如果我理解正确的话,您可能希望您的认证表看起来像:

CERTIFIED
id
bus_id
chauffer_id
...
...

The solution should be database agnostic. If I understand you correctly, you probably want your certified table to look like:

CERTIFIED
id
bus_id
chauffer_id
...
...
回心转意 2024-10-27 12:37:31

我能够找到的唯一解决方案是在父表中使用单个强制字段来表示“至少一个”,然后将 2 个或更多关系存储在交集表中。

司机

chauffeur_id
chauffer_name
certified_bus_id (not null)

认证的

chauffer_id
bus_id

公交车

bus_id
bus_name
certified_chauffer_id (not null)

要获取司机经过认证的所有公交车的列表,则

select c.chauffer_name, b.bus_name
from chauffeurs c
inner join busses b on (b.bus_id = c.certified_bus_id)
UNION
select c.chauffer_name, b.bus_name
from chauffeurs c
inner join certified ct on (c.chauffeur_id = ct.chauffer_id)
inner join busses b on (ct.bus_id = b.bus_id)

UNION(相对于 UNION ALL)负责使用 certified 中的值进行重复数据删除。

The only solution I've been able to find is the notion of a single mandatory field in the parent table to represent the "at least one" and then storing the 2 or more relationships in the intersection table.

chauffeurs

chauffeur_id
chauffer_name
certified_bus_id (not null)

certified

chauffer_id
bus_id

busses

bus_id
bus_name
certified_chauffer_id (not null)

To get a list of all busses where a chauffer is certified becomes

select c.chauffer_name, b.bus_name
from chauffeurs c
inner join busses b on (b.bus_id = c.certified_bus_id)
UNION
select c.chauffer_name, b.bus_name
from chauffeurs c
inner join certified ct on (c.chauffeur_id = ct.chauffer_id)
inner join busses b on (ct.bus_id = b.bus_id)

The UNION (vs UNION ALL) takes care of deduplication with the values in certified.

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