mysql和oracle实现递归_mysql以及oracle的递归查询

在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));

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值