gra*_*per 9 mysql database database-design one-to-many
我想创建两个表,一个带有注释,另一个带有回复,它们之间有一对多的关系.但如果他们也能回复回复怎么办呢?那该怎么办呢?这就是我对一对一的所有内容,但我不知道如果还有回复的答案应该如何.
    Comments:
•   Id
•   Title
•   Text
    Replies:
•   Id
•   Title
•   Text
•   Comment id
提前致谢.
mca*_*lex 15
您可以只使用一个表,其中包含一个ParentID字段.如果记录没有值,则为注释,否则为回复(对注释或回复).
您可以查询记录的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