views:

25

answers:

2

Suppose I have two columns in a table that represents a graph, the first column is a FROMNODE and second one is TONODE. What I would like to know is that how will we find all the nodes that are two steps away from a particular node. Lets suppose I have a node numbered '1' and i would like to know all the nodes that are two steps away from it.

I have tried(I am assuming the table name as graph) SELECT FROMNODE FROM GRAPH WHERE TONODE=1 (this is to select all the nodes that are connected to node 1, but I couldn't figure out how would I find all the nodes that are two steps away from node 1??)

A: 

Take it one step at a time!

select step2.tonode
from   graph step1
join   graph step2 on step2.fromnode = step1.tonode
where  step1.fromnode = 1
Jimmy
thanks for the response.....but, this gives 1 as one of the output node, which couldn't be possible, as we are starting from node 1 and looking at all the other nodes that are connected to node 1 and are two steps away from node 1.Lets say if 2 and 3 are connected to node 1 and 4,5 are connected to node 2....... 8,9 are connected to node 3.....then we have to find 4,5,8,9 as they are two steps away from node 1.
iecut
sorry for the confusion......you got it right way!!! thanks again.
iecut
A: 

Join back onto the same table...

SELECT g2.FromNode
FROM Graph as g1 
JOIN Graph as g2 ON g2.ToNode = g1.FromNode
WHERE g1.ToNode = @startnode
;
Rob Farley