简体   繁体   English

在Postgres中订购WITH RECURSIVE查询

[英]Ordering a WITH RECURSIVE query in Postgres

I'm executing a recursive query in Postgres to retrieve a list of emails and their threaded children as follows: 我在Postgres中执行递归查询以检索电子邮件及其线程子项列表,如下所示:

WITH RECURSIVE cte (id, title, path, parent_id, depth)  AS (
  SELECT  id, 
          title,
          array[id] AS path,
          parent_id, 
          1 AS depth
  FROM    emails
  WHERE   parent_id IS NULL

  UNION ALL

  SELECT  emails.id,
          emails.title,
          cte.path || emails.id,
          emails.parent_id, 
          cte.depth + 1 AS depth
  FROM    emails
          JOIN cte ON emails.parent_id = cte.id
)
SELECT id, title, path, parent_id, depth FROM cte
ORDER BY path;

How would go about changing the order of the list (for example sorting on title) before finding children emails. 如何在查找儿童电子邮件之前更改列表的顺序(例如,对标题进行排序)。 I obviously need to keep the outer ORDER BY so that the list is retrieved in it's tree order, and Postgres won't let me insert an ORDER BY clause before the UNION ALL. 我显然需要保留外部ORDER BY,以便按照树的顺序检索列表,Postgres不允许我在UNION ALL之前插入ORDER BY子句。

Thanks, 谢谢,

Create a view consisting of the first part of your query, ordered by title. 创建一个由查询的第一部分组成的视图,按标题排序。 Maybe something like this? 也许是这样的?

      CREATE VIEW title_Sort AS
      SELECT  id,  
      title, 
      array[id] AS path, 
      parent_id,  
      1 AS depth  
      FROM    emails 
      WHERE   parent_id IS NULL 
      ORDER BY title;

Then UNION ALL that view with your other query as you did before. 然后UNION ALL使用您之前执行的其他查询查看。 I think that will work. 我认为这会奏效。 On my netbook right now so I can't test :/ 在我的上网本上,所以我无法测试:/

This is untested, but usually i can add any ORDER BY before a union so long as there are parentheses... 这是未经测试的,但通常我可以在联合之前添加任何ORDER BY,只要有括号...

WITH RECURSIVE cte (id, title, path, parent_id, depth)  AS (
(  SELECT  id, 
          title,
          array[id] AS path,
          parent_id, 
          1 AS depth
  FROM    emails
  WHERE   parent_id IS NULL
  ORDER BY title
)
  UNION ALL

  SELECT  emails.id,
          emails.title,
          cte.path || emails.id,
          emails.parent_id, 
          cte.depth + 1 AS depth
  FROM    emails
          JOIN cte ON emails.parent_id = cte.id
)
SELECT id, title, path, parent_id, depth FROM cte
ORDER BY path;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM