sql - 我如何设计这两个表以防止损坏数据?

标签 sql postgresql database-design

我有一个 comments 表,一条评论引用一个答案或一个问题作为外键:

id primary key not null,
question_id  references questions(id),
answer_id references answers(id),

将填充 answer_idquestion_id,另一个将为空。

现在另一个表是notifications,每当创建评论时,我都会创建一个通知:

id primary key not null,
comment_id references comments(id),
question_id references questions(id),
answer_id references answers(id),

将填充 question_idanswer_id,但我想确保它与为该 comment 记录填充的内容一致。

如何确保通知将引用评论本身引用的相同资源?换句话说,如果我有一个引用问题的评论,然后我想为该评论创建一个通知但让它引用一个答案,数据库不应该允许这样做。我该如何施加这样的约束?

最佳答案

您应该规范化表格,并使用从通知到评论的引用来查找 question_id 和 answer_id。

create table comments (
  id serial primary key,
  question_id int references questions(id),
  answer_id int references answers(id)
);

create table notifications (
  id primary key not null,
  comment_id int references comments(id)
);

使用联接访问日期:

select question.*
from notifications
join comments on comments_id = comments.id
join questions on question_id = questions.id;

关于sql - 我如何设计这两个表以防止损坏数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44677953/

相关文章:

sql - 将 SQL 数据库升级/更新到新的模式版本,同时尽可能多地保留旧数据

sql - 选择两列值之间的记录

postgresql - 将同义词自定义词典添加到 Amazon RDS for PostgreSQL

json - PostgreSQL 查询/JSON

mysql - 单表 vs 多表

sql-server - 分层组的数据库架构

mysql - 多表 SQL SELECT 语句

sql - 如何在空白值上使用 PIVOT 子句

database - 使用 ansible playbook 运行 postgresql 命令。 Postgresql 需要密码

MySql 将多个组附加到用户