PostgreSQL
 sql >> Datenbank >  >> RDS >> PostgreSQL

Einfacher Graph-Suchalgorithmus in SQL (PostgreSQL)

Etwa so:

with recursive graph_cte (node1, node2, start_id) 
as
( 
  select node1, node2, id as start_id
  from graphs
  where node1 = 1 -- alternatively elect the starting element using where id = xyz
  union all
  select nxt.node1, nxt.node2, prv.start_id
  from graphs nxt
    join graph_cte prv on nxt.node1 = prv.node2
)
select start_id, node1, node2
from graph_cte
order by start_id;

(erfordert PostgreSQL 8.4 oder höher)