PostgreSQL-重新格式化查询退货顺序

时间:2019-06-20 14:19:21

标签: sql postgresql

我有一个递归查询,它返回一个非线性树,但是它首先返回所有的根节点。 (其中parent_id为null)

我将如何排序查询中获取一个根节点,获取整个树的行,然后获取第二个根节点,然后获取整个树...等等。

With RECURSIVE cte AS
(
   (
    SELECT * 
    FROM comments 
    WHERE thread_id = 1
      AND parent_id is NULL 
    ORDER BY upvoted DESC 
    FETCH FIRST 10 ROW ONLY
   )
   UNION
   SELECT t.*
   From comments t
     JOIN cte rt ON rt.comment_id = t.parent_id
 )
  SELECT cte.comment_id, cte.date_posted, cte.posted_by, cte.posted_by_user, cte.thread_id,
            cte.parent_id, cte.comments, cte.post_title, cte.posted_to_group, cte.upvoted, cte.downvoted,
            cte.depth, cv.user_id, cv.vote, cv.thread_id
     from cte LEFT JOIN
          commentsvoted cv
          ON cte.comment_id = cv.id
          AND cv.user_id = '82411580-6355-490e-be79- e7db9f561f66'

如果我添加:

ORDER BY coalesce(parent_id, comment_id), comment_id

对我的最后选择,它返回我所描述的内容除了,它会忽略:

ORDER BY upvoted DESC 

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以在order by中使用窗口功能:

ORDER BY MAX(upvoted) OVER (PARTITION BY coalesce(parent_id, comment_id)) DESC, 
         coalesce(parent_id, comment_id),   -- keep this in the event of ties,
         (case when parent_id is null then 1 else 0 end),
         comment_id