我正在 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 子句。
谢谢,
最佳答案
这是未经测试的,但通常我可以在联合之前添加任何 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;
关于sql - 在 Postgres 中订购 WITH RECURSIVE 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3228398/