查找联接表中两个ID之间的最短路径长度

时间:2019-07-19 18:35:45

标签: sql postgresql

假设我有一个这样的联接表

id1 | id2
1   | 2
2   | 3
3   | 4
4   | 5

我希望能够查询两个ID之间的距离。 因此,对于(1,2),它将为0。对于(1,5),它将为3。

1 个答案:

答案 0 :(得分:1)

您可以使用递归CTE遍历图并查找所有间接路径及其成本。例如:

with recursive
c as (
  select id1 as f, id2 as t, '/' || id1 || '/' || id2 as path, 0 as cost 
  from t where id1 = 1 -- starting node
  union
  select c.f, t.id2, path || '/' || t.id2, c.cost + 1
  from c
  join t on t.id1 = c.t
),
m as (
  select min(cost) as min_cost from c where t = 5
)
select c.*
from c
join m on c.cost = m.min_cost
where c.t = 5

结果:

f t path       cost
- - ---------- ----
1 5 /1/2/3/4/5    3

为了记录,这是我用来测试的数据脚本:

create table t (
  id1 int,
  id2 int
);

insert into t values (1, 2), (2, 3), (3, 4), (4, 5);

奖金查询(以相同的价格):如果您想列出所有可能的路径及其成本,则可以运行查询:

with recursive
c as (
  select id1 as f, id2 as t, '/' || id1 || '/' || id2 as path, 0 as cost from t
  union
  select c.f, t.id2, path || '/' || t.id2, c.cost + 1
  from c
  join t on t.id1 = c.t
)
select * from c

结果:

 f t path       cost 
 - - ---------- ---- 
 1 2 /1/2          0 
 2 3 /2/3          0 
 3 4 /3/4          0 
 4 5 /4/5          0 
 1 3 /1/2/3        1 
 2 4 /2/3/4        1 
 3 5 /3/4/5        1 
 1 4 /1/2/3/4      2 
 2 5 /2/3/4/5      2 
 1 5 /1/2/3/4/5    3