小编典典

如何在MYSQL中进行评论回复查询?

sql

我有评论回复(仅到一个级别)功能。所有评论最多可以包含回复,但是没有回复可以包含其进一步的回复。

所以我的数据库表结构如下

Id    ParentId    Comment
1     0           this is come sample comment text
2     0           this is come sample comment text
3     0           this is come sample comment text
4     1           this is come sample comment text
5     0           this is come sample comment text
6     3           this is come sample comment text
7     1           this is come sample comment text

在上述结构中,commentid,1(具有2个答复)和3(1个答复)具有答复。因此,要获取评论及其回复,一个简单的方法是首先获取所有ParentId为0的评论,然后运行while循环获取该特定commentId的所有回复。但是,如果我在特定记录上有大约200条评论,那似乎正在运行数百个查询。

因此,我想进行一个查询,该查询将按如下顺序获取带有评论的注释。

Id    ParentId    Comment
1     0           this is come sample comment text
4     1           this is come sample comment text
7     1           this is come sample comment text
2     0           this is come sample comment text
3     0           this is come sample comment text
6     3           this is come sample comment text    
5     0           this is come sample comment text

如果有人要在评论查询中使用此日期,则我的评论表中还会有一个评论日期列。

因此,最后我想使用一个mysql查询来获取所有评论及其回复。请告诉我我该怎么做?

谢谢


阅读 668

收藏
2021-03-10

共1个答案

小编典典

您可以在ORDER BY中使用表达式。试试这个:

SELECT *
FROM comments
ORDER BY IF(ParentId = 0, Id, ParentId), Id

如果ParentId = 0,将首先按ID排序,否则按ParentId排序。第二个排序标准是Id,以确保按顺序返回答复。

2021-03-10