MySQL中的广度优先搜索查询?

时间:2011-03-18 19:59:03

标签: mysql sql graph

我想构建一个mySQL查询,它从给定节点返回x深度图中的所有节点。深度只有2-4。

表结构是(neighborIDs可以包含多个值):

Id  Name  Desc  neighborIDs

因此,该任务基本上是mySQL中的广度优先搜索。我找到了way to do it in T-SQL,这在mySQL中是否可行? 单个SQL查询比编写PHP函数更好,它在节点的每个邻居上运行一个简单的SELECT(所以基本上可以进行大量的简单查询)?

感谢您的帮助


试一试:

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..

示例表是:

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

如果我使用输入id = 1运行查询,如果BFS深度为1,它应该返回id = 3的行。


另一次尝试:

SELECT id,neighborIDs
FROM locations
WHERE id = 3
OR
neighborIDs LIKE '%3%'
OR (SELECT neighborIDs FROM locations WHERE id = 3) LIKE CONCAT('%',id,'%')

此查询选择id = 3的节点的邻居。

2 个答案:

答案 0 :(得分:2)

正如我的评论中提到的那样,你的生活很艰难。 但类似于以下内容将在每个深度处生成邻居ID列表。 根据您的确切需要,结果集可以使用子查询并进一步操作以进行必要的操作(例如检索邻居的名称)。

SELECT  root.ID,
        d1.ID,
        d2.ID
FROM    Locations root
        LEFT JOIN Locations d1 ON
          root.Neighbours LIKE '%'+CAST(d1.ID as varchar)+'%'  --Or equivalent mysql pattern matching function
        LEFT JOIN Locations d2 ON
          d1.Neighbours LIKE '%'+CAST(d2.ID as varchar)+'%'

编辑:将INNER JOIN更改为LEFT JOIN

答案 1 :(得分:2)

步骤0:创建一个显示所有邻居对的视图

CREATE VIEW neighbour AS
( SELECT loc1.id AS a
       , loc2.id AS b
  FROM locations loc1
     , locations loc2
  WHERE FIND_IN_SET(loc1.id, loc2.neighbours)>0
     OR FIND_IN_SET(loc2.id, loc1.neighbours)>0
) ;

第1步:查找深度为1的邻居

SELECT b AS depth1
FROM neighbour
WHERE a = 1;               <-- for root with id=1

第2步:找到深度为2的邻居

SELECT DISTINCT d2.b AS depth2
FROM neighbour d1
  JOIN neighbour d2
    ON d1.b = d2.a
      AND d2.b != 1
WHERE d1.a = 1                <-- for root with id=1
  AND d2.b NOT IN
     ( SELECT b AS depth1     <- depth1 subquery
       FROM neighbour
       WHERE a = 1            <-- for root with id=1
      )
;

第3步:找到深度为3的邻居

SELECT d3.b as depth3
FROM neighbour d1
  JOIN neighbour d2
    ON d1.b = d2.a
    AND d2.b != 1
    AND d2.b NOT IN
       ( SELECT b as depth1
         FROM neighbour
         WHERE a = 1
       )
  JOIN neighbour d3
    ON d2.b = d3.a
    AND d3.b != 1
WHERE d1.a = 1
  AND d3.b NOT IN
     ( SELECT b as depth1
       FROM neighbour
       WHERE a = 1
      )
  AND d3.b NOT IN
     ( SELECT d2.b AS depth2
       FROM neighbour d1
         JOIN neighbour d2
           ON d1.b = d2.a
           AND d2.b != 1
       WHERE d1.a = 1
         AND d2.b NOT IN
            ( SELECT b AS depth1
              FROM neighbour
              WHERE a = 1
            )
     )
;

正如您所看到的,查询行数的增长是指数级的,所以我不会尝试4级。