小编Mik*_*ike的帖子

在递归 CTE 中计算父级的子级

我使用此查询来查找父母的评论id

WITH RECURSIVE cte (id, content, path, parent_id, depth)  AS (
    SELECT  id,
        content,
        array[id] AS path,
        parent_id,
        1 AS depth
    FROM    comment
    WHERE   id = 1

    UNION ALL

    SELECT  comment.id,
        comment.content,
        cte.path || comment.id,
        comment.parent_id,
        cte.depth + 1 AS depth
    FROM    comment
    JOIN cte ON comment.parent_id = cte.id
    WHERE depth < 3
    )
    SELECT id, content, path, parent_id, depth FROM cte
ORDER BY path LIMIT 200;
Run Code Online (Sandbox Code Playgroud)

除了我将深度限制为 3 之外,它运行良好。我怎样才能知道当前行是否有更多的孩子,如果有,请获取它们的数量,以便我可以显示数字,例如。“多加载 X”。

解决这个问题的最佳方法是什么?

这个小提琴中id4 和 …

postgresql cte recursive

2
推荐指数
1
解决办法
3538
查看次数

标签 统计

cte ×1

postgresql ×1

recursive ×1