【踩坑记录】MySQL 实现自定义递归函数
因项目需要,需根据某个商品类别path,查询该类别下的所有子类别
表 goods-categories(path,parent_id,id)
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。该处使用的表为临时创建的表 t1(id,parent_id,code)
最终成品代码:
DELIMITER //
drop function if exists f1;
create function f1(tableId int)
returns VARCHAR(200)
begin
declare p1 varchar(2000);
declare p2 varchar(200);
declare p3 varchar(200);
declare p4 varchar(200);
set p1 ='';
set p3 ='';
set p4 ='';
set p2 = cast(tableId as char);
while p2 is not null do
set p1 = concat(p1,',',p3);
set p4 = p2;
select group_concat(id) into p2 from t1
where find_in_set(parent_id,p2)>0;
select group_concat(code) into p3 from t1
where find_in_set(parent_id,p4)>0;
end while;
return p1;
end//
【错误1】: 函数结尾使用 end; 报错。
【解决方案】: 使用 DELIMITER // 定义结束符。因为MySQL默认【;】为结束符,但是函数中又避免不了要写sql,所以会提前遇到【;】导致不正常结束。所以定义// 为结束符,这样MySQL就能执行完整的函数结构体,而不是函数的中途的某个分号就执行了。
【错误2】:group_concat 函数使用错误,在sql后面增加了 group by id【其实这个地方使用id就是业务上的错误了】,导致了一次查询会有多条记录,而 select into 参数a ,返回多条记录时会报错;
【错误3!最大的错误】参数名 使用id , create function f1(id int)
导致出现了奇奇怪怪的问题,耗费了我大部分的时间。
