关系“OR”在关系数据库中
我想这个问题很微不足道。但尽管如此, 例如,我有实体:用户(id,名称),组(id,名称),user_group(user_id,group_id)和画廊(id,名称,owner_id)。 图库的所有者可以是用户或组。
关系数据库中最好的解决方案是什么?
谢谢!
PS 如果有人知道关系代数和模式优化。它会是什么样子?
我正在考虑 Owner (id, user_id, group_id),但我不知道如何用关系代数来表示“OR”关系。
The question is pretty trivial I guess. But nevertheless,
E.g., I have Entities: user (id, name), group (id, name), user_group (user_id, group_id) and gallery (id, name, owner_id).
Owner of the gallery could be user OR group.
What's the best solution for this in relational databases?
Thanks!
PS If anybody knows relational algebra and schema optimization. How will it look like?
I was thinking about Owner (id, user_id, group_id), but I don't have any idea how to show "OR" relation in terms of relational algebra.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
最简单的解决方案是一个关系
Owner(id, user_id, group_id)
,其中可以设置user_id
或group_id
——用一个适当的约束。将
Group
和User
折叠到一张表中会将多个一致性检查从数据库拖到应用程序逻辑中:User
和Group
,则可能需要进行更多调整。The simplest solution would be a relation
Owner(id, user_id, group_id)
where eitheruser_id
orgroup_id
can be set -- guard that with an appropriate constraint.Collapsing
Group
andUser
into one table drags several consistency checks from the database into the application logic:User
andGroup
are used in some more places more adaptions might be necessary.将所有者和组合并到一张表中。所有者和组的区别仅在于它们在此表中具有的属性,或者将新表与其自身连接在一起的关系表中存在/不存在行(“属于……的成员”)。
Combine owner and group into one table. Owner and group should only differ by the attributes they have in this table, or the presence / absence of rows in a relationtable joining this new table with itself ("is member of" ).
用户和组之间没有技术上的区别(只是概念上的区别)。
将它们放入同一个表 (
user
) 中,并在第二个字段中标记行的类型(组或用户)。使用应用程序逻辑确保在
user_group
表中只有 group 类型的行可以“有子级”。There is no technical difference between a user and a group (only a conceptual one).
Put them both into the same table (
user
) and flag a row's type (group or user) in a second field.Use application logic to make sure that only a row of type group may "have children" in the
user_group
table.引入一个新实体 OWNER 并使其成为 GROUP 的所有者。然后将 USER 和 GROUP 类别设为 OWNER(即“继承”它们)。
您的 ER 模型将如下所示(仅显示 PK 字段):
理论上,有 3 种主要方法在物理数据库中实现一个类别。它们都有优点和缺点,但对于您的模型来说,解决方案 1 可能是最合适的:
Introduce a new entity OWNER and make it owner of the GROUP. Then make USER and GROUP categories of (i.e. "inherit" them from) OWNER.
Your ER model would look like this (only PK fields shown):
Theoretically, there are 3 major ways to implement a category in the physical database. All of them have pros and cons, but for your model, the solution 1 is probably the most appropriate: