【问题标题】:Using a column in a CTE that does not exist in another table使用 CTE 中另一个表中不存在的列
【发布时间】:2020-06-23 20:52:31
【问题描述】:

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

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;

【问题讨论】:

    标签: sql postgresql select common-table-expression recursive-query


    【解决方案1】:

    我想你想要:

    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 的声明只是枚举列名(此处不应出现表前缀)。

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

    • UNION ALL 两边的查询必须返回相同的列数(对应于 cte 的声明)和相应的数据类型。

    【讨论】:

    • 联合的顶部有两列(与 CTE 定义中的列列表相符),但底部有三列。出事了。
    • @GMB 我现在收到此错误:错误:关系“consultantsandlevels”不存在详细信息:有一个名为“consultantsandlevels”的 WITH 项目,但无法从查询的这一部分引用它。提示:使用 WITH RECURSIVE,或重新排序 WITH 项以删除前向引用。
    • 如果有影响,我正在使用 postgresql
    • @ekeckeisen:我的错,RECURSIVE 关键字丢失了。固定。
    猜你喜欢
    • 2020-04-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-16
    • 2022-12-19
    • 1970-01-01
    相关资源
    最近更新 更多