Pra*_*ant 7 mysql sql comments
我正在评论回复(仅限一个级别)功能.所有评论都可以有多少回复,但没有回复可以进一步回复.
所以我的数据库表结构如下所示
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
Run Code Online (Sandbox Code Playgroud)
在上述结构中,有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
Run Code Online (Sandbox Code Playgroud)
我的评论表中还有一个评论日期列,如果有人想在评论查询中使用它.
最后,我想通过使用一个单独的mysql查询来获取所有注释及其回复.请告诉我怎么做?
谢谢
rod*_*ion 17
您可以在ORDER BY中使用表达式.试试这个:
SELECT *
FROM comments
ORDER BY IF(ParentId = 0, Id, ParentId), Id
Run Code Online (Sandbox Code Playgroud)
如果ParentId = 0,则首先按Id排序,否则按ParentId排序.第二个排序标准是Id,以确保按顺序返回回复.
| 归档时间: |
|
| 查看次数: |
3713 次 |
| 最近记录: |