簡體   English   中英

PostgreSQL-重新格式化查詢退貨順序

[英]Postgresql - Reformat Query return order

我有一個遞歸查詢,它返回一個非線性樹,但它首先返回所有的根節點。 (其中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 

在此處輸入圖片說明

您可以按以下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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM