【问题标题】:Database design - nullable fields数据库设计 - 可空字段
【发布时间】:2012-08-21 08:41:20
【问题描述】:

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

我有 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 将具有值)

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

谢谢

【问题讨论】:

  • 实际上,这与这个问题相同:Creating database table的可能重复
  • 很公平,但这个问题没有非常明确的答案!
  • 如果你愿意,我可以在这里给出同样的答案:)
  • 去吧...我看不出该链接问题的答案如何消除对可为空字段的需求,您能启发我吗?简单点!

标签: sql database postgresql database-design


【解决方案1】:

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

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
);

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

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

【讨论】:

  • 感谢 podiluska,很好的回答,您说服我采用标准化路线...(+1 使用 s 而不是 z)
  • 这个解决方案的“问题”是控制不同的用户不共享相同的通知。
  • @dotore 我不确定我是否理解您的评论?
  • @podiluska 如何防止不同的用户(或用户类型)共享相同的通知?
猜你喜欢
  • 2014-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-24
  • 1970-01-01
  • 1970-01-01
  • 2011-05-17
  • 1970-01-01
相关资源
最近更新 更多