---
title: "用select 语句中的START WITH...CONNECT BY PRIOR子句实现递归查询"
author: "sunsja"
date: "2008-05-12T10:44:47Z"
tags: []
slug: "select-start-with-connect-by-prior"
draft: false
lastmod: "2008-05-12T10:44:47Z"
id: 192143
url: "https://sunsja.iteye.com/blog/192143"
---

今天发现在oracle中的select语句可以用START WITH...CONNECT BY PRIOR子句实现递归查询，connect by 是结构化查询中用到的，其基本语法是：

select ... from tablename start with cond1  
connect by cond2  
where cond3;

简单说来是将一个树状结构存储在一张表里，比如一个表中存在两个字段:  
id,parentid那么通过表示每一条记录的parent是谁，就可以形成一个树状结构。

用上述语法的查询可以取得这棵树的所有记录。

其中COND1是根结点的限定语句，当然可以放宽限定条件，以取得多个根结点，实际就是多棵树。

COND2是连接条件，其中用PRIOR表示上一条记录，比如 CONNECT BY PRIOR ID=PRAENTID就是说上一条记录的ID是本条记录的PRAENTID，即本记录的父亲是上一条记录。

COND3是过滤条件，用于对返回的所有记录进行过滤。

 

 

# 对于oracle进行简单树查询(递归查询)

DEPTID PAREDEPTID NAME NUMBER NUMBER CHAR (40 Byte) 部门id 父部门id(所属部门id) 部门名称

通过子节点向根节点追朔.

Sql代码

**select** * **from** persons.dept start **with** deptid=76 **connect** **by** **prior** paredeptid=deptid   

通过根节点遍历子节点.

Sql代码

1. **select** * **from** persons.dept start **with** paredeptid=0 **connect** **by** **prior** deptid=paredeptid

 

可通过level 关键字查询所在层次.

Sql代码

1. **select** a.\*,**level** **from** persons.dept a start **with** paredeptid=0 **connect** **by** **prior** deptid=paredeptid

再次复习一下:start with ...connect by 的用法， start with 后面所跟的就是就是递归的种子。

递归的种子也就是递归开始的地方 connect by 后面的"prior" 如果缺省：则只能查询到符合条件的起始行，并不进行递归查询；

connect by prior 后面所放的字段是有关系的，它指明了查询的方向。

练习： 通过子节点获得顶节点

1. **select** FIRST\_VALUE(deptid) OVER (**ORDER** **BY** **LEVEL** **DESC** **ROWS** UNBOUNDED PRECEDING) **AS** firstdeptid **from** persons.dept start **with** deptid=76 **connect** **by** **prior** paredeptid=deptid