【问题标题】:How to represent a "active group" relationship in a relational database?如何在关系数据库中表示“活动组”关系?
【发布时间】:2017-08-01 11:40:53
【问题描述】:

我需要存储维护一个“用户”表,其中一个用户可以属于许多“组”。在每个组中,用户都有一组特定于组的设置。

使用 Group 表、User 表和 UserGroupSettings 交叉引用 [1] 表,这一切都非常容易实现。这里没有问题。

我正在努力解决的问题是如何表示用户与他们当前“活跃”的组之间的“活跃组”关系。用户可以是非活动的,也可以是一次在一个组中活动。当它们处于非活动状态时,它们的 UserGroupSettings 会保持不变。

在 User 表中有一个可以为空的“active_group”列的明显方法似乎不是最佳的,因为数据库架构不会强制执行这样一个事实:对于任何给定的 Group 和 User ID,UserGroupSettings 表中必须存在一行.同样,在 User 表中有一个“settings_id”外键列不会强制它指向的设置行实际上指向同一个用户。

有最优解吗?

  1. https://en.wikipedia.org/wiki/Associative_entity

【问题讨论】:

  • 我不明白这个问题。如果UserGroupSettings 中有一行,则用户将在组中处于非活动状态。您还可以将外键引用从 UserGroupSettings 返回到 User.ActiveGroup
  • UserGroupSettings 中的用户设置与 User.ActiveGroup 的设置无关。例如,您可以成为 2 个俱乐部的成员,但一次只能成为一个俱乐部的成员,或者没有(NULL)。问题是我不想编写代码来手动维护前提条件,即当 User1.ActiveGroup 设置为 Group1 时,UserGroupSettings 表中始终存在 (User1, Group1) 的相应条目。
  • 。 .使用外键引用很容易处理。
  • 我不明白怎么做?如果 UserGroupSettings 表包含 SettingsID(主键)、GroupID(外键)、UserID(外键)和一堆设置,我如何使 User.ActiveGroup 成为 SettingsID 的外键并仍然保证 UserGroupSettings.UserID = User.ID 按构造?仍然可以将用户插入到引用另一个用户的设置条目的数据库中。这并不比强制执行原始约束更好。

标签: sql database schema one-to-many database-normalization


【解决方案1】:

听起来您需要一个表,例如 user_active_group,其中包含一个引用用户组设置的外键。

类似的东西。 . .

-- Assumes {group_id, user_id) is unique. 
create table user_group_settings (
  settings_id integer primary key,
  user_id integer not null,
  group_id integer not null,
  bunch_of_settings char(1) not null default 'X',
  unique (user_id, group_id)
);

create table user_active_group (
  -- This primary key constraint means each user can have only one row.
  user_id integer not null primary key,
  group_id integer not null,
  -- This foreign key constraint means there must also be a row in user_group_settings.
  foreign key (user_id, group_id) references user_group_settings (user_id, group_id)
    on update cascade,
  active_group varchar(5) not null
);

级联更新似乎是明智的。级联删除更依赖于应用程序。

【讨论】:

    猜你喜欢
    • 2012-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-22
    • 2010-09-12
    • 2011-07-17
    • 1970-01-01
    相关资源
    最近更新 更多