不用写存储过程,不用建数据库函数,一段sql就可以实现

不用写存储过程,不用建数据库函数,一段sql就可以实现

不用写存储过程,不用建数据库函数,一段sql就可以实现

select
	id.level,
	data.* 
from
	(
	select
		@ids as _ids,
		( select @ids := group_concat( region_id ) from region where find_in_set(parent_id, @ids ) ) as cids,
		@l := @l + 1 as level 
	from
		region,
		( select @ids := 3, @l := 0 ) b 
	where
		@ids is not null 
	) id,
	region data 
where
	find_in_set( data.region_id, id._ids ) 
order by
	level

测试

--创建测试环境
create table t_test(
	id int primary key,
	parent_id int,
	name varchar(200)
)

insert t_test values(1,null,"中国");

insert t_test values(2,1,"华北");

insert t_test values(3,2,"山西省");
insert t_test values(4,2,"北京");

insert t_test values(5,3,"临汾市");
insert t_test values(6,4,"北京市");


insert t_test values(7,5,"尧都区");
insert t_test values(8,6,"朝阳区");

insert t_test values(9,7,"解放西路");
insert t_test values(10,8,"朝阳北路");


select * from t_test;

测试数据展示

查询 id=1,查询中国下边有哪些地方

select
	id.level,
	data.* 
from
	(
	select
		@ids as _ids,
		( select @ids := group_concat( id ) from t_test where find_in_set(parent_id, @ids ) ) as cids,
		@l := @l + 1 as level 
	from
		t_test,
		( select @ids := 1, @l := 0 ) b 
	where
		@ids is not null 
	) id,
	t_test data 
where
	find_in_set( data.id, id._ids ) 
order by
	level

id=3,查询山西下边有哪些地方

select
	id.level,
	data.* 
from
	(
	select
		@ids as _ids,
		( select @ids := group_concat( id ) from t_test where find_in_set(parent_id, @ids ) ) as cids,
		@l := @l + 1 as level 
	from
		t_test,
		( select @ids := 3, @l := 0 ) b 
	where
		@ids is not null 
	) id,
	t_test data 
where
	find_in_set( data.id, id._ids ) 
order by
	level

id=4,查询北京下边有哪些地方

最后再从 id=2 华北地区往下查询

总结 

到此这篇关于mysql利用父id递归向下查询子节点的文章就介绍到这了,更多相关mysql递归查询子节点内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!