I want to build a mySQL query that returns all nodes in a graph at depth x from the given node. Depth will be only 2-4.
Table structure (neighboring identifiers may contain several values):
Id Name Desc neighborIDs
Thus, the task is mainly to search by the Breadth method in mySQL. I found a way to do this in T-SQL , is this possible in mySQL? Is a single SQL query better than writing a PHP function that runs a simple SELECT for each node neighbor (so it basically makes a lot of simple queries)?
thanks for the help
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
Example table:
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 a query with input id id = 1, it should return a line with id = 3 if BFS goes 1 level deep.
Another attempt:
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 neighbors from node with id = 3.