使用递归查询循环访问表



我有以下数据:

cte1
=================
gp_id | m_ids
------|----------
1     | {123}
2     | {432,222}
3     | {123,222}

还有一个功能foobar(m_ids integer[]).该函数包含以下 cte:

with RECURSIVE foo as (
    select id, p_id, name from bar where id = any(m_ids)
    union all
    select b.id, b.p_id, b.name from bar b join foo f on f.p_id = b.id
)

该函数的使用方式如下:

select foobar(m_ids) from cte1;

现在,作为提高性能过程的一部分,我被告知要摆脱该功能。我的计划是在我的 cte 链中使用 cte foo,但我坚持尝试调整any(m_ids)的使用。

编辑:需要明确的是,问题是where id = any(m_ids)语句中使用的m_ids是函数的参数,所以我必须转换 cte 以使其在函数之外工作。

我想到了以下几点:

with RECURSIVE foo as (
    select (select id, p_id, name from bar where id = any(cte1.m_ids)
    union all
    select b.id, b.p_id, b.name from bar b join foo f on f.p_id = b.id)
    from cte1
)

但这行不通,因为
1( recursive query "foo" does not have the form non-recursive-term UNION [ALL] recursive-term
2( subquery must return only one column

最后,我想以这样的形式获取我的数据:

m_ids    |foobar_result 
---------|-------------
{123}    | 125        
{432,222}| 215        

也许JOIN那个表保存参数?

with RECURSIVE foo as (
    select m_ids, id, p_id, name from bar
    JOIN cte1 ON id = ANY(m_ids)
    union all
    select m_ids, b.id, b.p_id, b.name from bar b join foo f on f.p_id = b.id
)

最新更新