我想创建两个表,一个是评论,另一个是回复,它们之间是一对多的关系。但是如果他们也可以回复回复呢,那应该怎么改呢?这就是我对一对多的看法,但我不知道如果回复也可以回复,它应该是什么样子。
Comments:
• Id
• Title
• Text
Replies:
• Id
• Title
• Text
• Comment id
提前致谢。
最佳答案
您可以只使用一个表,其中包含一个 ParentID 字段。如果记录没有值(value),则为评论,否则为回复(对评论或回复)。
您可以查询记录的 ParentID 记录(检查它是 ParentID)以查看此回复是评论还是回复。
编辑:以上是一个相当实用的解决方案。但是,要使用规范化版本,仍然保留一个 Comments 表(没有 ParentID),并创建一个 ReplyTo 表,其中有 CommentID 和 ResponseID,两者都是 Comments 表中记录的 ID。
使用这个想法,下面的 sql 将显示评论和每个有评论的回复的“回复”:
select c.comment, r.comment as reply
from comment as c, comment as r, replyto as rt
where c.ID = rt.CommentID
and r.ID = rt.ReplyID
正如 Dimitrii 指出的那样,它不会显示没有回复的评论 - 为此你需要一个外部连接查询(没有测试语法):
SELECT c.comment, r.comment as reply,
from Comment c
left outer join Comment r on c.id = r.id
left outer join replyto rt on rt.responseid = r.id
关于mysql - 评论和回复的数据库设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13490609/