一尘不染

PostgreSQL递归自联接

sql

我在postgres中的表如下所示,表存储了ID之间的链式关系,我想查询一个可以产生类似“ vc1”->“ rc7”或“ vc3”->“
rc7”的结果的查询,仅查询第一列ID1中的ID

ID1     ID2
"vc1"   "vc2"
"vc2"   "vc3"
"vc3"   "vc4"
"vc4"   "rc7"

因此,我想在此处提供一些“ head” ID,为此我必须获取tail(链中的最后一个)ID。


阅读 150

收藏
2021-03-17

共1个答案

一尘不染

这是使用递归CTE的SQL:

with recursive tr(id1, id2, level) as (
      select t.id1, t.id2, 1 as level
      from t union all
      select t.id1, tr.id2, tr.level + 1
      from t join
           tr
           on t.id2 = tr.id1
     )
select *
from (select tr.*,
             max(level) over (partition by id1) as maxlevel
      from tr
     ) tr
where level = maxlevel;

是SQLFiddle

2021-03-17