---
title: "通用标准SQL的递归查询"
author: "ttkktt"
date: "2009-06-22T14:28:08Z"
tags: []
categories: ["企业架构"]
slug: "sql"
draft: false
lastmod: "2009-06-22T14:28:08Z"
id: 412875
url: "https://ttkktt.iteye.com/blog/412875"
---

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

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

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

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

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

有如下表tb（id，startpoint，endpoint）；

1　｜　Ａ　｜　Ｂ

2　｜　Ａ　｜　C

3　｜　Ａ　｜　Ｄ

4　｜　Ｂ　｜　Ｅ

5　｜　Ｃ　｜　Ｆ

6　｜　Ｄ　｜　Ｂ

7　｜　Ｅ　｜　I

8　｜　Ｇ　｜　Ｈ

查找出从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)

 

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