在 CTE 中使用另一个 table 中不存在的列

Using a column in a CTE that does not exist in another table

我是递归查询的新手,我正在尝试编写我的第一个递归查询。我正在尝试确定公司层次结构的级别,结果 table 包括两列 - 顾问 ID 和已由递归查询确定的级别。在 CTE 中,我不知道如何引用“level”,因为它是 table 中尚不存在的列。我做错了什么?

WITH consultantsandlevels
    (c."ConsultantDisplayID",
    consultantsandlevels."level"
    )

AS
(

SELECT c."ConsultantDisplayID",
    0

FROM flight_export_consultant AS c

WHERE c."ParentPersonDisplayID" IS NULL

UNION all

SELECT c."ConsultantDisplayID",

    c."ParentPersonDisplayID",

    consultantsandlevels."level" + 1
FROM flight_export_consultant

JOIN consultantsandlevels ON c."ParentPersonDisplayID" = consultantsandlevels."ConsultantDisplayID"
)

SELECT *

FROM consultantsandlevels;

我想你想要:

WITH RECURSIVE consultantsandlevels(ConsultantDisplayID, level) AS (
    SELECT "ConsultantDisplayID", 0 
    FROM flight_export_consultant 
    WHERE "ParentPersonDisplayID" IS NULL
    UNION ALL
    SELECT fec."ConsultantDisplayID", cal.level + 1
    FROM flight_export_consultant fec
    INNER JOIN consultantsandlevels cal 
        ON fec."ParentPersonDisplayID" = cal.ConsultantDisplayID
)
SELECT * FROM consultantsandlevels;

理由:

  • WITH 子句必须以关键字 RECURSIVE

    开头
  • comon-table-expression 的声明只是枚举列名(不应出现 table 前缀)。

  • level 初始设置为 0,然后您可以在每次迭代时通过引用相应的 common-table-expression 列来递增它。

  • UNION ALL 两侧的查询必须return 具有相应数据类型的相同列数(对应于 cte 的声明)。