sql - 数据库设计 - 可空字段

标签 sql database postgresql database-design

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

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

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

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

关于sql - 数据库设计 - 可空字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12051119/

相关文章:

mysql - 数据库规范化: How can I tabulate the data?

sql - SQL Server 中第一个实例 0 rest other 变成 1

python - 基于投票的用户之间的相似性

java - 错误 : Code too large

postgresql - 构建dockerfiile是可行的,但是从compose引用它并运行它失败。不确定是不是dockerfile文件路径错误?

mysql - mysql/sas 或 proc sql 中的分钟间隔

php - 带有准备语句的多个 AVG

postgresql - 什么是 Postgres 中的默认事务行级别和/或 Sequelize.js 中默认使用的 LOCK

c# - SQLite 数据库 (.db) 的性能问题

postgresql - 使用命令行恢复 postgres 备份文件?