【问题标题】:PostgreSQL: apply return of query to a functionPostgreSQL:将查询返回应用于函数
【发布时间】:2011-09-20 08:48:26
【问题描述】:

我有一个递归方法定义如下:

with recursive temp(id, s, r, e) as (
    select *
    from rel
    where rel_to_id = <parameter from sql query>

    union all

    select *
    from temp P
    inner join relationship C on P.r = C.s
)

我需要在从 SQL 查询返回的每一行上调用它,并在递归查询中定义列值(标记为)

我真的不想通过 python 调用 X 查询,这会减慢速度,必须有一种方法可以在 sql 中做到这一点。我试图在 plpgsql 中编写一个函数,但我无法定义返回类型 setof TABLE 并每次都取它的并集。

【问题讨论】:

  • 没有返回类型“setof TABLE”。它是TABLESETOF。见here

标签: sql postgresql common-table-expression


【解决方案1】:

我不确定我是否完全理解了这个问题,您的问题是根据您返回的值在 1 个以上的初始值上调用递归函数吗?

在这种情况下,您是否可以一次创建包含所有必需值的初始表,然后对其进行递归?像这样的:

with recursive temp(id, s, r, e) as (
    select *
    from rel r
    join <sql query> q on r.rel_to_id = q.id

    union all

    select *
    from temp P
    inner join relationship C on P.r = C.s
)

【讨论】:

  • 虽然不一定是 JOIN。也可以是一个简单的where rel_to_id IN (select some_id from some_value)
【解决方案2】:

恕我直言,多次调用递归查询,每个参数值一次是你能做的最糟糕的事情。相反,您应该将递归查询与提供参数值并迭代其“产品”的查询结合起来。通常将递归查询临时打包到视图中并将其与查询的另一段连接起来很方便。优化器会小心的。

CREATE VIEW temp_view AS (
    with recursive temp(id, s, r, e) as (
    SELECT *
    from rel
    WHERE {recursive_condition}
    -- Omit the restriction
    -- AND rel_to_id = <parameter from sql query>
    union /* all? */
    select *
    from temp P
    inner join relationship C on P.r = C.s
    WHERE {recursion_stopper}
    ) SELECT * FROM temp_view
);

-- Now join the recursive part
-- with the one that supplies the restrictions
SELECT ...
FROM temp_view tv
    , other_table ot
WHERE tv.parameter = ot.parameter
AND ... -- more stuff
;

【讨论】:

  • 感谢您的回答,我试过了,但是这个查询的结果是错误的,输出包含重复的列 ==> temp_view 有列 a、b、c 和 other_table 有相同的但输出这是:a,b,c,a,b,c
猜你喜欢
  • 2017-09-10
  • 2020-12-26
  • 2016-06-10
  • 2016-01-12
  • 2020-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-26
相关资源
最近更新 更多