Recursive query of mysql and oracle

 

There are many ways to implement recursive query in Oracle

Method 1: Recursion through the with clause

  1. withtemp(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.  fromtemp, t   
  8.  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

  1. SELECT id, parentid  
  2. FROM t  
  3. CONNECTBY id = PRIOR parentid   
  4. 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

  1. delimiter //  
  2. DROPFUNCTION IF EXISTS queryChildren;   
  3. CREATEFUNCTION `queryChildren` (areaId INT)   
  4. RETURNSVARCHAR(4000)   
  5. BEGIN  
  6. DECLARE sTemp VARCHAR(4000);  
  7. DECLARE sTempChd VARCHAR(4000);  
  8.   
  9. SET sTemp = '$';  
  10. SET sTempChd = cast(areaId aschar);   
  11.   
  12. WHILE sTempChd isnotNULL DO    
  13. SET sTemp = CONCAT(sTemp,',',sTempChd);  
  14. SELECT group_concat(id) INTO sTempChd FROM t_areainfo where FIND_IN_SET(parentId,sTempChd)>0;  
  15. END WHILE;  
  16. return sTemp;  
  17. END;  
  18. //  

Use this function in the sql statement

  1. select * from t_areainfo where find_in_set(id,queryChildrenAreaInfo(1)); 

 

 

 

This article comes from: http://blog.csdn.net/yangnianbing110/article/details/36664799

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326475469&siteId=291194637
Recommended