如何设计这两个表以防止损坏的数据



我有一个comments表,注释引用答案或问题作为外键:

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

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

现在另一个表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;
我认为

你把这变得过于复杂了。您应该有一个包含注释以及类型的表。 无需空值,并已规范化

CREATE TABLE comments (
 id INT PRIMARY KEY,
 comment VARCHAR,
 is_answer BOOLEAN
);

最新更新