>  기사  >  데이터 베이스  >  树状结构表中,获取指定节点的所有父节点路径

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

WBOY
WBOY원래의
2016-06-07 14:55:081217검색

树状结构表中,获取指定节点的所有父节点路径,为了方便查看,我增加了节点的id。 无 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

树状结构表中,获取指定节点的所有父节点路径,为了方便查看,我增加了节点的id。
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`, `name`, `parent_group_id`) values (2, 'b', -1);
insert into `group` (`id`, `name`, `parent_group_id`) values (3, 'c',  1);


/**
 * 返回树状结构表中指定节点的父节点路径.
 * 张露兵 zhanglubing927@163.com
 * 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)
성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.