2

有点“最佳实践”的问题,因为我是数据库设计的新手,我想确保我在正确的轨道上使用这个

我有 3 种用户类型,用户(单人)、组(很多用户)和公司(很多组),每个都有自己的登录名,允许他们发布消息。所以例如。如果一家公司发布一条消息,它将出现在所有链接用户的新闻提要中。

为了实现这一点,我有一个存储消息内容的表“消息”,以及用于链接用户类型的外键

我打算使用以下模式(PostgreSQL)来实现这一点......

create table notifications(
    notification_id serial primary key,
    user_id integer references users,
    group_id integer references groups,
    company_id integer references companies,
    date_created timestamp not null default now(),
    title_id text not null,
    message_id text not null,
    icon text not null default 'logo'
);
comment on table notifications is 'Messages to be displayed on a users home feed';

这将允许我构建一个查询,为用户新闻提要提取相关消息(例如,只有一个字段 user_id、group_id 或 company_id 将具有值)

但这是最好的方法吗?我确信拥有可为空的外键是一个坏主意,我在想使用一种枚举键可能会有更好的解决方案?(这甚至存在吗?!)

谢谢

4

1 回答 1

4

一种高度规范化的选择是使表格更像

create table notifications( 
    notification_id serial primary key, 
    date_created timestamp not null default now(), 
    title_id text not null, 
    message_id text not null, 
    icon text not null default 'logo' 
); 

create table usernotifications
(
    notification_id integer references notifications,
    user_id integer references users
);

create table groupnotifications
(
    notification_id integer references notifications,
    group_id integer references groups
);

create table companynotifications
(
    notification_id integer references notifications,
    company_id integer references companies
);

其中条目仅存在于任何给定通知的相关(用户/公司/组)通知表中。

(在表明外键是可选的情况下,我认为可空外键没有任何问题,但类似类型的多个外键确实给人一种非规范化设计的印象)

于 2012-08-21T09:27:09.410 回答