There are many ways to implement recursive query in Oracle
Method 1: Recursion through the with clause
- withtemp(id,parentid) as (
- select id,parentid
- from t
- where t.id = '1'
- union all
- select t.id, t.parentid
- fromtemp, t
- wheretemp.parentid = t.id)
The recursive with clause in the with clause achieves the effect of recursive query
Method 2: Implemented through connect by provided by oracle
- SELECT id, parentid
- FROM t
- CONNECTBY id = PRIOR parentid
- START WITH id = '1';
Prior means downward recursion in front of parentid, and upward recursion in front of id
Implementation of recursion in MySQL :
MySQL does not provide the syntax of connect by, nor the with clause, so how to do it? We define a function implementation
- delimiter //
- DROPFUNCTION IF EXISTS queryChildren;
- CREATEFUNCTION `queryChildren` (areaId INT)
- RETURNSVARCHAR(4000)
- BEGIN
- DECLARE sTemp VARCHAR(4000);
- DECLARE sTempChd VARCHAR(4000);
- SET sTemp = '$';
- SET sTempChd = cast(areaId aschar);
- WHILE sTempChd isnotNULL 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;
- //
Use this function in the sql statement
- select * from t_areainfo where find_in_set(id,queryChildrenAreaInfo(1));
This article comes from: http://blog.csdn.net/yangnianbing110/article/details/36664799