PL/pgSQL 函数接受参数并递归搜索 table

PL/pgSQL function taking argument and searching table recursively

我是 PL/pgSQL 的新人。我们有一个 Postgres 11 数据库。

我需要一个将 1 个参数作为一个 table 的 ID 并在另一个中进行递归搜索的函数。它应该 return 两列:id 和连接结果作为 text(或 varchar)。

这是我的代码(更像是伪代码):

DROP FUNCTION IF EXISTS;
CREATE OR REPLACE FUNCTION my_awesome_func(AUID, UUID) RETURNS (RESULT TEXT) AS;
DECLARE RESULT TEXT;
BEGIN;
SELECT first_table.parent_uid FROM first_table WHERE first_table.auid = AUID; 
WITH RECURSIVE child_to_parents AS (
    SELECT second_table.* FROM second_table
        WHERE aoguid = first_table.parent_uid
    UNION ALL
    SELECT second_table.* FROM second_table.*, child_to_parents
        WHERE second_table.aoguid = child_to_parents.parentguid
            AND second_table.currstatus = 0
    )
END
    SELECT * FROM child_to_parents ORDER BY aolevel;

fiddle 在这里:
https://dbfiddle.uk/?rdbms=postgres_11&fiddle=dfa2838ab11356cc08987d0931f7b8e5

您所说的函数可能如下所示:

CREATE OR REPLACE FUNCTION my_awesome_func(_auid uuid, OUT _ancestors text)
  LANGUAGE plpgsql AS
$func$
BEGIN
   WITH RECURSIVE child_to_parents AS (
      SELECT t1.auid, t1.parent_uid, 1 AS lvl
      FROM   first_table t1
      WHERE  t1.auid = _auid 

      UNION ALL
      SELECT c.auid, t2.parentguid, lvl + 1
      FROM   child_to_parents c
      JOIN   second_table t2 ON t2.aoguid = c.parent_uid
                            AND t2.currstatus = 0
      )
   SELECT string_agg(c.parent_uid::text, E'\n'  ORDER BY c.lvl)
   FROM   child_to_parents c
   INTO   _ancestors;
END
$func$;

在您的问题不清楚的地方填​​写假设。

普通查询不需要 PL/pgSQL 函数包装器。一个普通的 SQL 函数,或者只是简单的查询就可以了(可能更快)。

具有更多解释和链接的相关答案:

  • Join two tables using id and descendants from tree like table
  • Retrieving full hierarchy sorted by a column under PostgreSQL's Ltree module