PGSQL 递归 根据父节点查询所有子节点

     WITH RECURSIVE temp_table AS (
            SELECT id,
                   parent_comment_id,
                   CONTENT,
                   create_time,
                   create_by
            FROM
                t_comment
            WHERE
                parent_comment_id = #{pId}
              AND is_valid = 1
              AND is_top = 2 UNION
            SELECT A.ID,
                   A.parent_comment_id,
                   A.CONTENT,
                   A.create_time,
                   A.create_by
            FROM
                t_comment A,
                temp_table b
            WHERE
                A.parent_comment_id = b.ID
              and is_valid=1 and is_top=2
        ) SELECT
            *
        FROM
            temp_table
        ORDER BY
            create_time DESC;

注意 不要用union all 否则效率会很慢

你可能感兴趣的:(sql,数据库,mysql)