有点“最佳实践”的问题,因为我是新的数据库设计,我想确保我在正确的轨道上与这一个
我有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具有值)
但这是最好的方法吗?我确信拥有可以为空的外键是个坏主意,我在想使用枚举键可能会有更好的解决方案?(这甚至存在吗?)!)
谢谢
最佳答案
一个高度标准化的选择是使表格更像
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
);
对于任何给定的通知,条目只存在于相关的(用户/公司/组)通知表中。
(我认为在外键是可选的情况下,可以为空的外键没有任何问题,但是多个相似类型的外键确实给人一种非规范化设计的印象)