在自参考表中查询父母和孩子 [英] Query parents and children in self-referencing table

查看:67
本文介绍了在自参考表中查询父母和孩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 MySQL 中有一个注释表格,如下所示:

I have a Comments table like below, in MySQL:

content           created_at                 id  parent_id
"second comment", 2014-06-03T10:08:44+0000,  37,      -1
"third comment",  2014-06-03T10:10:35+0000,  40,      -1
"Under third",    2014-06-03T10:10:44+0000,  41,      40
"Under second",   2014-06-03T10:11:59+0000,  42,      37

用户可以添加条评论,该评论将没有parent_id,因为它们不是其他评论的子级;用户还可以回复对通过先前方法添加的评论,因此它们是主要评论的子级,例如在第二层级上. parent_id 列表示父注释的ID(如果有).如果评论没有父项,则默认 parent_id 为-1.

Users can add new comments, which won't have a parent_id, as they are not children of other comments; users can also reply to comments that have been added through the previous method, so they are children of the primary comments, like on a second level of hierarchy. The parent_id column represents the id of a parent comment, if present. If the comment doesn't have a parent, default parent_id is -1.

话虽如此,我想查询表中的所有注释,每个父项后跟其子级,由created_at ASC 排序.来自上述数据集的示例:

That being said, I would like to query all the comments from the table, each parent followed by its children, ordered by created_at ASC. Example from the above data set:

second comment
Under second
third comment
Under third

我考虑使用GROUP BY,因为它类似于分组策略,但实际上并未将所有子级分组到单个行中.这种查询的解决方案是什么?有更多类型的解决方案吗?

I thought of using GROUP BY, as it resembles a grouping strategy, but not actually grouping all children into a single row. What would be a solution to this kind of query ? Are there more types of solutions ?

推荐答案

它没有测试,但我认为这也应该在MySQL中起作用:

It didn't test but i think this should work in MySQL too:

ORDER BY CASE WHEN parent_id=-1 THEN id ELSE parent_id END, created_at

如果您不能假设ID以与注释相同的逻辑顺序升序,则它会变得更加复杂:

If you cannot assume the Ids to be ascending in the same logical order as the Comments, it get's a little more complex:

SELECT parent_id,id,created_at parent_date,null child_date,content
    FROM Comments
    WHERE parent_id=-1
UNION
SELECT c.parent_id,c.id,p.created_at as parent_date,c.created_at as child_date,c.content
FROM Comments c
    JOIN (SELECT id,created_at,content
            FROM Comments
            WHERE parent_id=-1
            GROUP BY id,created_at,content) p ON p.id=c.parent_id
ORDER BY parent_date,child_date

这篇关于在自参考表中查询父母和孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆