1、創建表:
create table `tree` (
`id` int(11) not null auto_increment comment '主鍵',
`parent_id` int(11) not null,
`name` varchar(10) not null,
primary key (`id`)
) engine=innodb default charset=utf8;
2、數據:
insert into `tree` (`id`, `parent_id`, `name`) values('1','0','根節點');
insert into `tree` (`id`, `parent_id`, `name`) values('2','1','一級節點a');
insert into `tree` (`id`, `parent_id`, `name`) values('3','1','一級節點b');
insert into `tree` (`id`, `parent_id`, `name`) values('4','1','一級節點c');
insert into `tree` (`id`, `parent_id`, `name`) values('5','3','二級節點aa');
insert into `tree` (`id`, `parent_id`, `name`) values('6','4','二級節點bb');
insert into `tree` (`id`, `parent_id`, `name`) values('7','2','二級節點cc');
insert into `tree` (`id`, `parent_id`, `name`) values('8','5','三級節點aaa');
insert into `tree` (`id`, `parent_id`, `name`) values('9','5','三級節點bbb');
insert into `tree` (`id`, `parent_id`, `name`) values('10','5','三級節點ccc');
insert into `tree` (`id`, `parent_id`, `name`) values('11','6','三級節點ddd');
insert into `tree` (`id`, `parent_id`, `name`) values('12','11','四級節點aaaa');
insert into `tree` (`id`, `parent_id`, `name`) values('13','10','四級節點bbbb');
3、遞歸的函數:
drop function if exists getChildList;
delimiter //
create function `getChildList`(rootId int) returns varchar(1000)
begin
declare result varchar(1000);
declare tempChild varchar(1000);
set result = '';
set tempChild =cast(rootId as char);
while tempChild is not null do
set result = concat(result,',',tempChild);
select group_concat(id) into tempChild from tree where find_in_set(parent_id,tempChild)>0;
end while;
return result;
end //
delimiter ;
4、查詢
tree 表所有的數據,如下:
4.1、 查詢1
select getChildList(1);
結果: ,1,2,3,4,5,6,7,8,9,10,11,12,13
4.2、 查詢1
select getChildList(2);
結果:,2,7
4.3、 查詢2
select * from tree where find_in_set(id, getChildList(2));
4.4、 查詢3
select * from tree where find_in_set(id, getChildList(3));
4.5、 查詢4
select * from tree where find_in_set(id, getChildList(4));