sql >> Base de Datos >  >> RDS >> PostgreSQL

Consulta SQL de PostgreSQL para atravesar un gráfico no dirigido completo y devolver todos los bordes encontrados

Llegué a esto, no debería entrar en bucles infinitos con ningún tipo de datos:

--create temp table edges ("from" text, "to" text);
--insert into edges values ('initial_node', 'a'), ('a', 'b'), ('a', 'c'), ('c', 'd');

with recursive graph(points) as (
  select array(select distinct "to" from edges where "from" = 'initial_node')
  union all
  select g.points || e1.p || e2.p
  from graph g
  left join lateral (
    select array(
      select distinct "to"
      from edges 
      where "from" =any(g.points) and "to" <>all(g.points) and "to" <> 'initial_node') AS p) e1 on (true)
  left join lateral (
    select array(
      select distinct "from"
      from edges 
      where "to" =any(g.points) and "from" <>all(g.points) and "from" <> 'initial_node') AS p) e2 on (true)
  where e1.p <> '{}' OR e2.p <> '{}'
  )
select distinct unnest(points)
from graph
order by 1

Las consultas recursivas son muy limitantes en términos de lo que se puede seleccionar, y dado que no permiten usar los resultados recursivos dentro de una subselección, no se puede usar NOT IN (select * from recursive where...). Almacenar los resultados en una matriz, usando LEFT JOIN LATERAL y usando =ANY() y <>ALL() resolvió este enigma.