2010-07-02 45 views
1

我有存储在表中的大图的邻接列表。MySQL:提取子图?

v1 | v2 
1 | 2 
1 | 3 
1 | 4 
2 | 5 
3 | 5 
3 | 6 
4 | 7 
7 | 9 
5 | 10 

我试图提取图2跳远离说顶点1,使其返回从上面的列表中的所有边缘除(7,9)和(5,10)。我管理这个:

SELECT * FROM stub_graph WHERE v1 IN (SELECT v1 FROM stub_graph WHERE v1=1 UNION select v2 FROM stub_graph WHERE v1=1) ; 

我不是特别满意我的原因有两个解决方案:

  1. IN
  2. 这是能够 提取链接,如1-2和2存在-5 但我无法提取链接 ,如6-7。

有没有很好的方法来做到这一点?

万一有人有兴趣在创建表时,这里的SQL代码:

create table stub_graph(v1 int(11), v2 int(11)); 
insert into stub_graph VALUES(1,2); 
insert into stub_graph VALUES(1,3); 
insert into stub_graph VALUES(1,4); 
insert into stub_graph VALUES(2,5); 
insert into stub_graph VALUES(3,5); 
insert into stub_graph VALUES(3,6); 
insert into stub_graph VALUES(4,7); 
insert into stub_graph VALUES(6,7); 
insert into stub_graph VALUES(7,9); 
insert into stub_graph VALUES(5,10); 

回答

2

试试这个:

SELECT g1.v1 as Root, g2.v1 as Next g3.v1 as Final FROM stub_graph g1 
    LEFT JOIN stub_graph g2 on g2.v1 = g1.v2 
    LEFT JOIN stub_graph g3 on g3.v1 = g2.v2 
WHERE g1.v1 = 1 

如果你想(6-7),但你需要去因为它距离1(1-3,3-6,6-7)3跳。

如果你想要任意深入,你需要看看递归存储过程,我认为MySQL的后续版本支持,但这看起来适合你的需求。或者,下面的链接还有一些其他的想法。

应该产量:

Root | Next | Final 
    1 | 3 |  5 
    1 | 3 |  6 
    1 | 2 |  5 
    1 | 4 |  7 

也见this link on Hierarchical Data