Monday, 24 September 2018

Finding a Path in General Graph in SQL (Source: Joe Celkos)


Source -------------------- Destination

Each edge is having a wt =1
There are 5 Noes in graph

s,u,x,v,y


CREATE TABLE Graph
(
source CHAR(2) NOT NULL,
destination CHAR(2) NOT NULL,
cost INTEGER NOT NULL,
PRIMARY KEY (source, destination)
);


INSERT INTO graph VALUES ('s','s','0') ;
INSERT INTO graph VALUES ('s','u','3') ;
INSERT INTO graph VALUES ('s','x','5') ;
INSERT INTO graph VALUES ('u','u','0') ;
INSERT INTO graph VALUES ('u','v','6') ;
INSERT INTO graph VALUES ('u','x','2') ;
INSERT INTO graph VALUES ('v','v','0') ;
INSERT INTO graph VALUES ('v','y','2') ;
INSERT INTO graph VALUES ('x','u','1') ;
INSERT INTO graph VALUES ('x','v','4') ;
INSERT INTO graph VALUES ('x','x','0') ;
INSERT INTO graph VALUES ('x','y','6') ;
INSERT INTO graph VALUES ('y','s','3') ;
INSERT INTO graph VALUES ('y','v','7') ;
INSERT INTO graph VALUES ('y','y','0') ;


CREATE TABLE paths (
    step_1        CHAR(2) NOT NULL,
    step_2        CHAR(2) NOT NULL,
    step_3        CHAR(2) NOT NULL,
    step_4        CHAR(2) NOT NULL,
    step_5        CHAR(2) NOT NULL,
    total_cost    INTEGER NOT NULL,
    path_length   INTEGER NOT NULL,
    PRIMARY KEY ( step_1,
                  step_2,
                  step_3,
                  step_4,
                  step_5 )
);   

----------------

SELECT
    g1.source,  --it is ‘s’ in this example
    g2.source,
    g3.source,
    g4.source,
    g4.destination, --it is ‘y’ in this example
    ( g1.cost + g2.cost + g3.cost + g4.cost ) total_cost,
    (
        CASE
            WHEN g1.source NOT IN (g2.source,g3.source,g4.source) THEN 1
            ELSE 0
        END
        +
        CASE
            WHEN g2.source NOT IN (g1.source,g3.source,g4.source) THEN 1
            ELSE 0
        END
        +
        CASE
            WHEN g3.source NOT IN (g1.source,g2.source,g4.source) THEN 1
            ELSE 0
        END
        +
        CASE
            WHEN g4.source NOT IN (g1.source,g2.source,g3.source) THEN 1
            ELSE 0
        END
    ) path_length
FROM
    graph G1,
graph G2,
Graph  G3,graph  g4
WHERE
    g1.source = 's'
    AND g1.destination = g2.source
        AND g2.destination = g3.source
            AND g3.destination = g4.source
                AND g4.destination = 'y';







No comments:

Post a Comment