在Oracle中实现递归查询的途径较多
方法1:通过with子句实现递归
- with temp(id,parentid) as (
- select id,parentid
- from t
- where t.id = '1'
- union all
- select t.id, t.parentid
- from temp, t
- where temp.parentid = t.id)
with子句中递归with子句达到递归查询的效果
方法2:通过oracle提供的connect by来实现
- SELECT id, parentid
- FROM t
- CONNECT BY id = PRIOR parentid
- START WITH id = '1';
prior在parentid前面表示向下递归,在id前面向上递归
MySQL中递归的实现:
mysql中没有提供connect by这种语法,也没有with子句,那么怎么搞呢?我们定义一个函数实现
- delimiter //
- DROP FUNCTION IF EXISTS queryChildren;
- CREATE FUNCTION `queryChildren` (areaId INT)
- RETURNS VARCHAR(4000)
- BEGIN
- DECLARE sTemp VARCHAR(4000);
- DECLARE sTempChd VARCHAR(4000);
- SET sTemp = '$';
- SET sTempChd = cast(areaId as char);
- WHILE sTempChd is not NULL DO
- SET sTemp = CONCAT(sTemp,',',sTempChd);
- SELECT group_concat(id) INTO sTempChd FROM t_areainfo where FIND_IN_SET(parentId,sTempChd)>0;
- END WHILE;
- return sTemp;
- END;
- //
在sql语句使用该函数
- select * from t_areainfo where find_in_set(id,queryChildrenAreaInfo(1));
本文来源于:http://blog.csdn.net/yangnianbing110/article/details/36664799