gpt4 book ai didi

sql - 如何在 PostgreSQL 中对递归查询进行排序

转载 作者:行者123 更新时间:2023-12-04 07:19:48 26 4
gpt4 key购买 nike

我有 sql 查询来查找来自原始评论的所有回复:

WITH RECURSIVE children AS (
SELECT blog_comments_comment.*, 0 AS relative_depth
FROM blog_comments_comment
WHERE id in %s

UNION ALL

SELECT blog_comments_comment.*, children.relative_depth + 1
FROM blog_comments_comment,children
WHERE blog_comments_comment.reply_to_id = children.id
)
SELECT id,post_id, name,body, reply_to_id, relative_depth
FROM children
ORDER BY children;
我怎样才能对它进行排序以使其成为这样?
-main comment
---reply to main comment
------reply to reply
----------etc
---2nd reply to main comment
------reply to 2nd reply
----------etc

最佳答案

维护路径并排序:

WITH RECURSIVE children AS (
SELECT bcc.*, 0 AS relative_depth,
array[bcc.id] as path
FROM blog_comments_comment bcc
WHERE id in %s
UNION ALL
SELECT bcc.*, c.relative_depth + 1,
path || c.id
FROM children c JOIN
blog_comments_comment bcc
ON bcc.reply_to_id = bcc.id
)
SELECT id,post_id, name,body, reply_to_id, relative_depth
FROM children
ORDER BY path;
Here是一个db<> fiddle 。

关于sql - 如何在 PostgreSQL 中对递归查询进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68575278/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com