加入收藏 | 设为首页 | 会员中心 | 我要投稿 常州站长网 (https://www.0519zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MySql教程 > 正文

树状结构表中,获取指定节点的所有父节点路径

发布时间:2020-12-31 14:48:05 所属栏目:MySql教程 来源:网络整理
导读:以下代码由PHP站长网 52php.cn收集自互联网 现在PHP站长网小编把它分享给大家,仅供参考 drop table if exists `group`;create table `group` (`id` int(11) not null auto_increment,`parent_group_id` int(11) not null default '-1',`name` varchar(255

以下代码由PHP站长网 52php.cn收集自互联网

现在PHP站长网小编把它分享给大家,仅供参考

drop table if exists `group`;

create table `group` (
	`id` int(11) not null auto_increment,`parent_group_id` int(11) not null default '-1',`name` varchar(255) not null,primary key (`id`)
);

insert into `group` (`id`,`name`,`parent_group_id`) values (1,'a',-1);
insert into `group` (`id`,`parent_group_id`) values (2,'b',`parent_group_id`) values (3,'c',1);


/**
 * 返回树状结构表中指定节点的父节点路径.
 * 张露兵 [email?protected]
 * 2012-2-21
 */
drop procedure if exists get_path;

delimiter $
create procedure get_path(in id int) 
begin

	declare gid int default id; 
	declare path varchar(255) default '';
	
	while gid is not null and gid != -1 do
		select concat(concat(g.name,'(',g.id,')'),'-',path),g.parent_group_id into path,gid 
		from `group` g where g.id = gid;
	end while;
	
	select substring(path,1,length(path)-1) 'path'; 
end
$

-- call get_path(3);
-- a(1)-c(3)

以上内容由PHP站长网【52php.cn】收集整理供大家参考研究

如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。

(编辑:常州站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读