当前位置: 代码迷 >> SQL >> 通用基准SQL的递归查询
  详细解决方案

通用基准SQL的递归查询

热度:45   发布时间:2016-05-05 13:06:30.0
通用标准SQL的递归查询

近日转移数据库遇到一个递归查询问题,相信不少朋友在开发中都会遇到,通常特定数据库都有特定的实现。例如Oracle可以用

Select * from …. Where [结果过滤条件语句]

Start with? [and起始条件过滤语句]

Connect by prior [and中间记录过滤条件语句]?

但是用非标准的sql来实现会和数据库绑定,当你的项目要变更数据库时会遇到你的程序逻辑运行出错。几经思考发现可以用标准sql自连接来实现递归功能,例子:

有如下表tb(id,startpoint,endpoint);

1 | A | B

2 | A | C

3 | A | D

4 | B | E

5 | C | F

6 | D | B

7 | E | I

8 | G | H

查找出从A出发可以到达的目的点。(结果应该是B,C,D,E,F,I)

?

(select a from

(select table1.endpoint a,table2.endpoint b

from tb table1, tb table2

where table1.endpoint=table2.startpoint) newtable1)

union

(select b from

(select table1.endpoint a,table2.endpoint b

from tb table1, tb table2

where table1.endpoint=table2.startpoint) newtable2)

?

实现完后发现性能不怎么样,希望有朋友有更好的实现可以共享下。


?

?

  相关解决方案