SQL

数据库设计-可为空的字段

发布于 2021-06-15 11:03:59

因为我是数据库设计的新手,所以有一个“最佳实践”问题,我想确保自己在正确的方向上工作

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

为此,我有一个表“ messages”来存储消息内容以及用于链接用户类型的外键

我打算使用以下架构(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将具有值)

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

谢谢

关注者
0
被浏览
95
1 个回答
  • 面试哥
    面试哥 2021-06-15
    为面试而生,有面试问题,就找面试哥。

    高度标准化的一种选择是使表更像

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

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

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



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看