Best Way to Store/Access a Directed Graph

后端 未结 6 620
清酒与你
清酒与你 2021-02-01 09:14

I have around 3500 flood control facilities that I would like to represent as a network to determine flow paths (essentially a directed graph). I\'m currently using SqlServer an

6条回答
  •  情歌与酒
    2021-02-01 09:53

    I know nothing about flood control facilities. But I would take the first facility. And use a temp table and a while loop to generate the path.

    -- Pseudo Code
    TempTable (LastNode, CurrentNode, N)

    DECLARE @intN INT SET @intN = 1

    INSERT INTO TempTable(LastNode, CurrentNode, N) -- Insert first item in list with no up stream items...call this initial condition SELECT LastNode, CurrentNode, @intN FROM your table WHERE node has nothing upstream

    WHILE @intN <= 3500 BEGIN SEt @intN = @intN + 1 INSERT INTO TempTable(LastNode, CurrentNode, N) SELECT LastNode, CurrentNode, @intN FROM your table WHERE LastNode IN (SELECT CurrentNode FROM TempTable WHERE N = @intN-1)

    IF @@ROWCOUNT = 0
         BREAK
    

    END

    If we assume that every node points to one child. Then this should take no longer than 3500 iterations. If multiple nodes have the same upstream provider then it will take less. But more importantly, this lets you do this...

    SELECT LastNode, CurrentNode, N FROM TempTable ORDER BY N

    And that will let you see if there are any loops or any other issues with your provider. Incidentally 3500 rows is not that much so even in the worst case of each provider pointing to a different upstream provider, this should not take that long.

提交回复
热议问题