PostgreSQL
 sql >> Database >  >> RDS >> PostgreSQL

Condizione di arresto CTE ricorsiva per i loop

WITH RECURSIVE paths AS (
    -- For simplicity assume node 1 is the start
    -- we'll have two starting nodes for data = 1 and 2
    SELECT DISTINCT
        src           as node
        , data        as data
        , 0           as depth
        , src::text   as path
        , ''          as edgeAdded   
    FROM edges
    WHERE
        src = 1

    UNION ALL

    SELECT DISTINCT
        edges.dst
        , edges.data
        , depth + 1
        , paths.path || '->' || edges.dst::text
        , edges.src::text || '->' || edges.dst::text
    FROM paths
    JOIN edges ON edges.src = paths.node AND edges.data = paths.data
    AND NOT paths.path LIKE '%' || edges.dst::text || '%' 
        -- AND eliminate loops?
)
SELECT * FROM paths;

Qui con la condizione AND NOT paths.path LIKE '%' || edges.dst::text || '%' stiamo evitando i bordi posteriori che porterebbero a un loop.
http:/ /www.sqlfiddle.com/#!12/086ee/1