如何在关系数据库中表示“活动组”关系?

时间:2017-03-11 00:49:15

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

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

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

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

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

是否有最佳解决方案?

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

1 个答案:

答案 0 :(得分:0)

听起来你需要一个表,例如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
);

级联更新似乎合情合理。级联删除更依赖于应用程序。