mysql - 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
解决方案
如果我正确理解你的问题,我认为这个查询会做你想要的。我稍微修改了你的小提琴,为评论 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
推荐阅读
- reactjs - Material-UI 中带有样式的伪选择器未呈现到页面
- php - 用 php 7 配置 MSSQL
- php - 用php删除部分字符串
- c# - 如何以编程方式将样式设置为 TextAppearance.DeviceDefault.Medium?
- javascript - 返回值不显示以及如何传递使用输入按钮接收的值
- firefox - 带有引导程序的 Mozilla 开发工具错误
- android - Android DataBinding - 为什么数据绑定不支持@mipmap 图像
- c# - 在 Chrome Selenium 上找不到文本框
- heroku - 将域名连接到 Heroku 应用程序时出现问题
- amazon-web-services - AWS S3:IA 与 One-Zone IA 存储类