mysql以及oracle的递归查询

来源:互联网 发布:亚马逊和淘宝哪个大 编辑:程序博客网 时间:2024/05/02 06:08

在oracle中实现递归查询的途径较多

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

[sql] view plaincopy
  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 plaincopy
  1. SELECT id, parentid  
  2. FROM t  
  3. CONNECT BY id = PRIOR parentid  
  4. START WITH id = '1';  

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


mysql中递归的实现:

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

[sql] view plaincopy
  1. delimiter //  
  2. DROP FUNCTION IF EXISTS queryChildren;  
  3. CREATE FUNCTION `queryChildren` (areaId INT)  
  4. RETURNS VARCHAR(4000)  
  5. BEGIN  
  6. DECLARE sTemp VARCHAR(4000);  
  7. DECLARE sTempChd VARCHAR(4000);  
  8.   
  9. SET sTemp = '$';  
  10. SET sTempChd = cast(areaId as char);  
  11.   
  12. WHILE sTempChd is not NULL 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. //  
在sql语句使用该函数

[sql] view plaincopy
  1. select * from t_areainfo where find_in_set(id,queryChildrenAreaInfo(1));  
0 0