SQL - 当之前有另一个查询时,WITH RECURSIVE 不起作用

SQL - WITH RECURSIVE doesn't work, when there is another query before

我有一个 (postgresql) 查询,就像

with 
recursive account_tree as (<recursive function depending on path>), -- 1
path as (<some other query>)                                        -- 2
select * from account_tree;

这很好用。

但是当我重新排序 with 查询时

with 
path as (<some other query>),                                      -- 2
recursive account_tree as (<recursive function depending on path>) -- 1
select * from account_tree;

突然显示语法错误。当我有标准的非递归查询时,不会发生这种行为。对于非递归查询,我可以随心所欲地进行排序。

为什么要这样做?

无论哪个 CTE 实际上是递归的,recursive 关键字总是紧跟在 WITH 之后:

with recursive path as (
  <some other query>
), account_tree as (
  <recursive function depending on path>
)
select * 
from account_tree;

recursive 指的是整个 with 子句。所以只需使用:

with recursive path as (<some other query>),                                      -- 2

recursive真正 的意思是 Postgres 将首先搜索“table”名称作为 CTE,然后在 tables/views CTE 的递归部分。问题实际上是解决标识符。它对其他 CTE 没有影响。