I want to build a mySQL query, which returns all nodes in a graph in x depth from a given node. The depth will be only 2-4.
The table structure is (neighborIDs can contain multiple values):
Id Name Desc neighborIDs
So the task is basically a Breadth-first search in mySQL. I have found a way to do it in T-SQL, is this possible in mySQL?
Is a single SQL query better, than writing a PHP function, that runs a simple SELECT on every neighbour of a node (so basically making tons of simple queries)?
Thanks for help
A try:
SELECT root.ID,
d1.ID,
d2.ID
FROM Locations root
LEFT JOIN Locations d1 ON
root.neighborIDs LIKE CONCAT('%',d1.id,'%')
LEFT JOIN Locations d2 ON
d1.neighborIDs LIKE CONCAT('%',d2.id,'%')
WHERE root.id = 1 # i guess this defines the starting node for the search..
An example table is:
id name desc neighborIDs
1 id1 --
2 id2 ---
3 id3 neighborours are 1,2 1,2
4 id4 neighbour is 3 3
10 id10 neigh is 4 4
If i run the query with the input id=1, it should return the row with id=3 if the BFS goes 1 level deep.
Another try:
SELECT id,neighborIDs
FROM locations
WHERE id = 3
OR
neighborIDs LIKE '%3%'
OR (SELECT neighborIDs FROM locations WHERE id = 3) LIKE CONCAT('%',id,'%')
This query selects the neighbors of the node with id = 3.
step 0: Create a view that shows all neighbour pairs
step 1: Find neighbours of depth 1
step 2: Find neighbours of depth 2
step 3: Find neighbours of depth 3
As you can see, the growth is exponential for the number of query lines, so I won’t try the level 4.