ITeye博客

mysql以及oracle的递归查询

lihaiming · 2017-02-09 14:58 · 数据库 · 数据库 · 递归 · prior · Markdown

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

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

[sql] view plain 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 copy

  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 plain copy

  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. SET sTemp = '$';
  9. 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)>0;
  13. END WHILE;
  14. return sTemp;
  15. END;
  16. //

在sql语句使用该函数

[sql] view plain copy

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

 

 

 

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

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。