递归sql查询调用

时间:2013-12-07 05:19:11

标签: sql oracle recursion

我有下表,表示从角到角的街道

street    |  from        |  to 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
street1   |  node11      |  node2222
street1   |  node2222    |  node111
street1   |  node111     |  node4
street1   |  node4       |  node1212
street1   |  node1212    |  node6
street1   |  node6       |  node7
street1   |  node7       |  node8
street99  |  node2222    |  node111
street99  |  node111     |  node4

我希望能够通过一个递归查询获取street1的数据 使用“from”等于“node2222”,最后一个数据的“to”等于“node6” 结果必须是顺序的,一行的“to”成为下一行的“from”。

我可以在基本查询中执行此操作,但它只会返回1个数据,因此我必须按顺序调用它4次以获得整个序列

select street, from , to where street = 'street1'  AND from = 'node2222'

第二次调用查询,结果来自#1

select street, from , to where street = 'street1'  AND from = (call #1).to

依旧......

如果找到所有节点或者它将返回到目前为止发现的内容,那么“递归”查询Id的结果将会是这样的:

street    |  from        |  to 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
street1   |  node2222    |  node111
street1   |  node111     |  node4
street1   |  node4       |  node1212
street1   |  node1212    |  node6

是否可以在一个查询中的SQL中执行此操作

非常感谢

1 个答案:

答案 0 :(得分:0)

请尝试:

select distinct street,
  "from", 
  "to"
From YourTable
where street='street1'
connect by nocycle "from" = prior "to" and "to"<='node6'
start with "from"='node2222'

SQL Fiddle Demo