首页 > 解决方案 > MySQL:将填充了 parent_id 的行放在父 id 之后

问题描述

我有一个包含 3 列 comment_id、comment 和 parent_comment_id 的表。查询始终限制为 10,我必须在这 10 个结果中返回所有 comment_id,后跟具有先前 comment_id 的 parent_comment_id 的行。

示例:comment_id 2 在 comment_id 20 中有答案,其 parent_comment_id 设置为 2。我需要结果如下所示:

comment_id ... parent_comment_id
2                0
20               2
3                0
4                0
5                0
15               5
...

有什么好的订购方式吗?这是示例数据:http ://sqlfiddle.com/#!9/70120c/5

标签: mysql

解决方案


如果我正确理解你的问题,我认为这个查询会做你想要的。我稍微修改了你的小提琴,为评论 1 添加了另一个评论回复(新版本在这里)。排序有点棘手,第一个术语将评论及其回复排序在一起,然后第二个术语对该组中的评论进行排序(因此 1 及其回复 3 和 15 按该顺序排序)。DISTINCT需要防止有多个回复的评论出现多个输出行。

SELECT DISTINCT c.comment_id,c.comment,c.parent_comment_id
FROM comments c
LEFT JOIN comments r ON c.comment_id = r.parent_comment_id
ORDER BY IF(c.parent_comment_id=0, c.comment_id, c.parent_comment_id), c.comment_id
LIMIT 10;

输出:

comment_id  comment                                             parent_comment_id
1           The earth is flat                                   0
3           Response to 1                                       1
15          Another response to 1                               1
2           One hundred angels can dance on the head of a pin   0
14          Response to 2                                       2
4           The earth is like a ball.                           0
6           Response to 4                                       4
5           The earth is like a ball.                           0
7           The earth is like a ball.                           0
8           The earth is like a ball.                           0

推荐阅读