---
title: " mysql以及oracle的递归查询 "
author: "lihaiming"
date: "2017-02-09T14:58:46Z"
tags: ["prior", "递归"]
categories: ["数据库"]
slug: "mysql-oracle"
draft: false
lastmod: "2017-02-09T14:58:46Z"
id: 2356306
url: "https://lihaiming.iteye.com/blog/2356306"
---

在[Oracle](http://lib.csdn.net/base/oracle "Oracle知识库")中实现递归查询的途径较多

方法1：通过with子句实现递归

**\[sql]** [view plain](http://blog.csdn.net/yangnianbing110/article/details/36664799 "view plain") [copy](http://blog.csdn.net/yangnianbing110/article/details/36664799 "copy")

1. with temp(id,parentid) as (
2. select id,parentid
3. from t
4. where t.id = '1'
5. union all
6. select t.id, t.parentid
7. from temp, t
8. where temp.parentid = t.id)

with子句中递归with子句达到递归查询的效果

方法2：通过oracle提供的connect by来实现

**\[sql]** [view plain](http://blog.csdn.net/yangnianbing110/article/details/36664799 "view plain") [copy](http://blog.csdn.net/yangnianbing110/article/details/36664799 "copy")

1. SELECT id, parentid
2. FROM t
3. CONNECT BY id = PRIOR parentid
4. START WITH id = '1';

prior在parentid前面表示向下递归，在id前面向上递归

 

[MySQL](http://lib.csdn.net/base/mysql "MySQL知识库")中递归的实现：

mysql中没有提供connect by这种语法，也没有with子句，那么怎么搞呢？我们定义一个函数实现

**\[sql]** [view plain](http://blog.csdn.net/yangnianbing110/article/details/36664799 "view plain") [copy](http://blog.csdn.net/yangnianbing110/article/details/36664799 "copy")

01. delimiter //
02. DROP FUNCTION IF EXISTS queryChildren;
03. CREATE FUNCTION \`queryChildren\` (areaId INT)
04. RETURNS VARCHAR(4000)
05. BEGIN
06. DECLARE sTemp VARCHAR(4000);
07. DECLARE sTempChd VARCHAR(4000);
08. SET sTemp = '$';
09. SET sTempChd = cast(areaId as char);
10. WHILE sTempChd is not NULL DO
11. SET sTemp = CONCAT(sTemp,',',sTempChd);
12. SELECT group\_concat(id) INTO sTempChd FROM t\_areainfo where FIND\_IN\_SET(parentId,sTempChd)&gt;0;
13. END WHILE;
14. return sTemp;
15. END;
16. //

在sql语句使用该函数

**\[sql]** [view plain](http://blog.csdn.net/yangnianbing110/article/details/36664799 "view plain") [copy](http://blog.csdn.net/yangnianbing110/article/details/36664799 "copy")

1. select * from t\_areainfo where find\_in\_set(id,queryChildrenAreaInfo(1));

 

 

 

本文来源于：http://blog.csdn.net/yangnianbing110/article/details/36664799