使用 PGSQL 的评论树

Tree of comments with PGSQL

我的评论树有简单的评论示例:

1. comment_id_1
    - comment_id_3
        * commnet_id_5
        * commnet_id_6
    - comment_id_4
        * commnet_id_7
        * commnet_id_8
2. comment_id_2
    - comment_id_9
    - comment_id_10
id | parent_id
---+------------
1  |  null
2  |  null
3  |  1
4  |  1
5  |  3
6  |  3
7  |  4
8  |  4
9  |  2
10 |  2

我想获取给定评论或给定评论列表的所有子评论,从parent_id = 1content_id = 1开始。我进行了查询,但它失败了。

WITH RECURSIVE sub_comments AS (
    SELECT com.parent_id, com.id
    FROM comments com
    UNION
    SELECT c.parent_id, c.id
    FROM comments c
         JOIN sub_comments sc ON c.id = sc.parent_id
)
SELECT *
FROM sub_comments
WHERE parent_id IS NOT NULL

我只需要向 select 添加一个(或多个)特殊“分支”评论吗?

我失败了:

WITH RECURSIVE sub_comments AS (
    SELECT com.parent_id, com.id
    FROM comments com
    WHERE com.parent_id = 1
    UNION
    SELECT c.parent_id, c.id
    FROM comments c
         JOIN sub_comments sc ON c.id = sc.parent_id
)
SELECT *
FROM sub_comments
WHERE comment_id IS NOT NULL

替代解决方案是添加这样的限制,但我找不到限制条件的方法。

WITH RECURSIVE sub_comments AS (
    SELECT com.parent_id, com.id
    FROM comments com
    UNION
    SELECT c.parent_id, c.id
    FROM comments c
         JOIN sub_comments sc ON c.id = sc.parent_id
)
SELECT *
FROM sub_comments
LIMIT 4 (but limit should count only if parent_it IS NULL)

您的第二次尝试接近成功,但您翻转了连接条件。当查询树时,您从根节点开始,然后重复将子节点添加到结果集中,直到没有留下父节点在结果集中但本身不在结果集中的行。

WITH RECURSIVE sub_comments AS (
    SELECT com.parent_id, com.id
    FROM comments com
    WHERE com.id = 1 -- start with the root itself, not its children
  UNION
    SELECT c.parent_id, c.id
    FROM comments c
    JOIN sub_comments sc ON c.parent_id = sc.id -- or: WHERE c.parent_id IN (SELECT id FROM sub_comments)
)
SELECT *
FROM sub_comments