MySQL中根据父节点查询其所有子节点

原文地址:http://jingyan.baidu.com/article/647f01158ee0da7f2148a80b.html


DROP FUNCTION IF EXISTS `fun_get_children`;
DELIMITER ;;
CREATE DEFINER=`root`@`127.0.0.1` FUNCTION `fun_get_children`(i_id int(32)) RETURNS varchar(20000) CHARSET utf8
    DETERMINISTIC
begin
declare _result varchar(20000);
declare _ids varchar(20000);
set _result = cast(i_id as char);
set _ids = cast(i_id as char);
while _ids is not null do
set _result = concat(_result, ',', _ids);
select group_concat(m.tree_id) into _ids 
from module m where find_in_set(m.parent_id, _ids) > 0;
end while;
return _result;
end;
DELIMITER ;


--调用方式
1. select fun_get_children(1);
2. select * from module where find_in_set(id, fun_get_children(1)); 


PS:1. 没有DETERMINISTIC关键字会报错。

2.结果中会有重复值,但作为查询子条件对最终结果没有影响。

3.最好为function而不是procedure,如果是后者无法在sql用调用方式的两种方法进行调用。

4.如果在查询语句的where条件中应该用find_in_set(str, strList)关键字,如:where find_in_set(id, fun_get_modules(1))。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值