在Postgres中订购WITH RECURSIVE查询

时间:2010-07-12 12:16:04

标签: sql postgresql recursion

我正在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;

如何在查找儿童电子邮件之前更改列表的顺序(例如,对标题进行排序)。我显然需要保留外部ORDER BY,以便按照树的顺序检索列表,Postgres不允许我在UNION ALL之前插入ORDER BY子句。

谢谢,

2 个答案:

答案 0 :(得分:2)

创建一个视图,其中包含查询的第一部分,按标题排序。也许是这样的?

      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;

然后UNION ALL使用您之前执行的其他查询查看。我认为这会奏效。在我的上网本上,所以我无法测试:/

答案 1 :(得分:2)

这是未经测试的,但通常我可以在联盟之前添加任何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;