无法加入 CTE 内的 CTE 列,未知列

Can't JOIN on CTE column inside CTE, unknown column

我正在努力实现以下...

with 
    relations as (
        select
            rm.recordId,
            rs.fieldId,
            rm.relationSettingId,
            rm.relatedRecordId
        from relationMapping rm
            left join relationSetting rs on rs.id = rm.relationSettingId
    ),
    foo as (
        select distinct 
            coalesce(rnff.fieldId, field.id)
        from field
            left join relationNameFromField rnff 
                on rnff.relationSettingId = relations.relationSettingId  -- <---- Won't work
    )

select * from foo;

我收到以下错误:

Unknown column 'relations.relationSettingId' in 'on clause'

为什么我不能引用 relations table?

根据您的 CTE,这只是一个猜测,但我认为您可能想要:

with 
relations as (
    select
        rm.recordId,
        rs.fieldId,
        rm.relationSettingId,
        rm.relatedRecordId
    from relationMapping rm
    left join relationSetting rs
        on rs.id = rm.relationSettingId
),
foo as (
    select distinct 
        coalesce(rnff.fieldId, field.id)
    from field
    left join relations                        --add this join here
        on field.id = relations.fieldId
    left join relationNameFromField rnff 
        on rnff.relationSettingId = relations.relationSettingId
)
select * from foo;

我们不知道您的 table 结构,所以我不能说我有适合该连接的列,但我认为这是一个很有根据的猜测。