postgres中带有链中参数的递归查询

recursive query in postgres with a parameter in chain

用这个table


CREATE TABLE table1
    ("v1" text, "v2" text)
;
    
INSERT INTO table1
    ("v1", "v2")
VALUES
    ('vc1', 'vc2'),
    ('vc2', 'vc3'),
    ('vc3', 'vc4'),
    ('vc4', 'rc7')
;

我有这个问题

    WITH RECURSIVE chain(from_id, to_id) AS (
      SELECT NULL, 'vc1'
      UNION
      SELECT c.to_id, ani.v2
      FROM chain c
      LEFT JOIN table1 ani ON (ani.v1 = to_id)
      WHERE c.to_id IS NOT NULL
    )
    SELECT to_id FROM chain;

我曾尝试在 cte 中对 'vc1' 进行参数化,但遇到了困难,在网上或文档中也没有看到任何相关信息。

我试过了

SELECT NULL, where to_id = ?

然后

SELECT to_id from chain where to_id='vc1';

有没有一种简单的方法可以将参数插入到 cte 中?

您可以在 CTE 的 root/anchor 查询中提供参数。但是你需要在递归部分从实际的tableselect:

WITH RECURSIVE chain AS (
  select "applicationNodeInstanceId", "nextNodeInstanceId"
  from appnodeinstance     
  where "applicationNodeInstanceId" = 'vc1' --<< this can be a parameter
  UNION all
  SELECT c."applicationNodeInstanceId", c."nextNodeInstanceId"
  FROM appnodeinstance c
    JOIN chain ani ON c."applicationNodeInstanceId" = ani."nextNodeInstanceId"
)
SELECT * 
FROM chain;