E
E
eldar_web2018-11-20 14:20:44
PostgreSQL
eldar_web, 2018-11-20 14:20:44

How to collect all interchanges in SQL?

No ideas come to mind yet.
How can I use a SQL query (used by Postgresql) to collect interchanges by group?
Let's say there is a table Foo with the structure:

main | cross
x | a
x | b
b | x
b | h
z | t
....

main interchanges cross , and vice versa. It is necessary to collect all interchanges in one line.
The output should output a group:
1) x - a - b - h
2) z - t
How can I implement it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Telepnev, 2018-11-21
@TelepnevDmitriy

with recursive table_recursive as (
  with "table" as (
    select *
    from (
      values('x','a'),
      ('a','b'),
      ('b','c'),
      ('c','d'),
      ('n','k'),
      ('k','l')
    ) as _(main,"cross")
  )
  select *, t.main || ' -> ' || t."cross" as "path"
  from "table" as t
  
  union
  
  select t_r.main, t."cross", t_r."path" || ' -> ' || t."cross" as "path"
  from table_recursive t_r
  join "table" t on t.main = t_r."cross"
)
select t_r.*
from table_recursive t_r
where
  t_r."main" not in (select "cross" from table_recursive)
  and t_r."cross" not in (select "main" from table_recursive)

It should be borne in mind that in this interpretation, if the table is large, then it will be fullscan
I didn’t figure out how to deal with it right away

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question