简体   繁体   中英

Undirected graph in Oracle SQL

I'm trying to represent undirected graph in Oracle SQL, for example, I have stations graph:

CREATE TABLE station (
   station_id INTEGER NOT NULL
);

CREATE TABLE station_link (
  from_station INTEGER NOT NULL,
  to_station INTEGER NOT NULL
);

This is obviously directed graph, but I have no idea, how to make it undirected.

Point : I need to get all vertices, which have path to current vertex and information about their level (how many vertices on this path).

For directed graph it is pretty easy:

SELECT sl.to_station, LEVEL
  FROM station_link sl
START WITH sl.from_station = :curVertex
CONNECT BY NOCYCLE PRIOR sl.to_station = sl.from_station

But so we will get only one-way verticies.

Question: Do this problem have solution, except adding additional links (2 -> 1 for 1 -> 2)?

There is sql fiddle for tests: http://sqlfiddle.com/#!4/6c09e/24

For a "fast win" you can use your structure "as is", but for every edge you shold have two records in station_link table.

If you want "not_so_fast_but_without_doble_edge_records_please win", you can use this weirdo-trick:

SELECT
  x.TO_STATION,
  x.LVL
FROM (
        SELECT sl.to_station, LEVEL as lvl
          FROM station_link sl
        START WITH sl.from_station = :curVertex 
        CONNECT BY NOCYCLE PRIOR sl.to_station = sl.from_station 
        UNION ALL
        SELECT sl.from_station as to_station , LEVEL as lvl
          FROM station_link sl
        START WITH sl.to_station = :curVertex 
        CONNECT BY NOCYCLE PRIOR sl.from_station = sl.to_station
) x

It will do the work. Actually, it just combines two traversal directions.

But if I'll want to implement some serious algorithms on graphs in PLSQL, I would look to SDO_GEOMETRY data type and Oracle Spatial And Graphs Datasheets.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM