当前位置: 代码网 > it编程>数据库>Mysql > mysql实现向下递归与向上递归方式

mysql实现向下递归与向上递归方式

2026年04月17日 Mysql 我要评论
1、表描述find_in_set:类似sql的in查询查询多个节点的数据,这个函数可以换成=号进行关联,=关联时只能查询一个节点的数据,表名称: t_table名称描述code数据标识pcode数据父

1、表描述

find_in_set:类似sql的in查询查询多个节点的数据,这个函数可以换成=号进行关联,=关联时只能查询一个节点的数据,

表名称: t_table

名称描述
code数据标识
pcode数据父标识

2、向下递归查询

select t3.*
-- 层级需要
-- ,t2.level_
from( 
	select @code as _code, 
        (select @code := group_concat(code) 
            from t_table 
            where find_in_set(pcode, @code) 
        ) as t1 
        -- 层级需要
        -- ,@level := @level+1 as level_
    from t_table, 
		(select @code := 'code1,code2,...'
				-- 层级需要
				-- ,@level := -1
		) t4
		where @code is not null 
) t2, t_table t3 
where find_in_set(t3.code, t2._code) 
-- 不包含自身
-- and !find_in_set(t3.code,'code1,code2,...')

3、向上递归查询

select t3.* 
-- 层级需要
-- ,t2.level_
from( 
	select @code as _code, 
		(select @code := group_concat(pcode) 
			from t_table 
			where find_in_set(code,@code)
		) as t1
		-- 层级需要
        -- ,@level := @level+1 as level_
	from t_table, 
		(select @code := 'code1,code2,...'
				-- 层级需要
				-- ,@level := -1
		) t4 
		where @code is not null 
	) t2, t_table t3
where find_in_set(t3.code, t2._code) 
-- 不包含自身
-- and !find_in_set(t3.code,'code1,code2,...')

4、总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com