如何从表格中获取评论和评论的回复

时间:2017-08-19 19:16:51

标签: mysql sql database database-design

我有一张评论表。

Table

我想从表格中获取评论和回复,以便像这样显示它们。我只是在寻找一个查询,所以我可以做这样的事情

What I Want

我做了什么 我使用的查询

SELECT c.post_id, c.id AS comment_id, c.user_id, users.username, c.created, c.comment, r.id AS reply_id, r.parent_comment_id, r.created, r.comment AS reply, r.user_id AS reply_user_id, r_user.username as reply_username FROM (comments c) LEFT JOIN comments r ON c.id = r.parent_comment_id LEFT JOIN users ON c.user_id = users.id LEFT JOIN users as r_user ON r.user_id = r_user.id  WHERE r.id OR c.post_id IS NOT NULL ORDER BY parent_comment_id ASC;

What I Did

1 个答案:

答案 0 :(得分:1)

也许是这样的:

SELECT
  c.comment,
  IFNULL(r.comment, '') reply
FROM 
  comments c
  LEFT JOIN comments r
    ON c.id = r.parent_comment_id 
WHERE 
  c.parent_comment_id is null