SQL如何实现MYSQL的递归查询
众所周知,目前的mysql版本中并不支持直接的递归查询,但是通过递归到迭代转化的思路,还是可以在一句sql内实现树的递归查询的。这个得益于mysql允许在sql语句内使用@变量。以下是示例代码。
创建表格
create table `treenodes` ( `id` int , -- 节点id `nodename` varchar (60), -- 节点名称 `pid` int -- 节点父id );
插入测试数据
insert into `treenodes` (`id`, `nodename`, `pid`) values ('1','a','0'),('2','b','1'),('3','c','1'), ('4','d','2'),('5','e','2'),('6','f','3'), ('7','g','6'),('8','h','0'),('9','i','8'), ('10','j','8'),('11','k','8'),('12','l','9'), ('13','m','9'),('14','n','12'),('15','o','12'), ('16','p','15'),('17','q','15'),('18','r','3'), ('19','s','2'),('20','t','6'),('21','u','8');
查询语句
select id as id,pid as 父id ,levels as 父到子之间级数, paths as 父到子路径 from ( select id,pid, @le:= if (pid = 0 ,0, if( locate( concat('|',pid,':'),@pathlevel) > 0 , substring_index( substring_index(@pathlevel,concat('|',pid,':'),-1),'|',1) +1 ,@le+1) ) levels , @pathlevel:= concat(@pathlevel,'|',id,':', @le ,'|') pathlevel , @pathnodes:= if( pid =0,',0', concat_ws(',', if( locate( concat('|',pid,':'),@pathall) > 0 , substring_index( substring_index(@pathall,concat('|',pid,':'),-1),'|',1) ,@pathnodes ) ,pid ) )paths ,@pathall:=concat(@pathall,'|',id,':', @pathnodes ,'|') pathall from treenodes, (select @le:=0,@pathlevel:='', @pathall:='',@pathnodes:='') vv order by pid,id ) src order by id
最后的结果如下:
id 父id 父到子之间级数 父到子路径
------ ------ -------------------- -------------------
1 0 0 ,0
2 1 1 ,0,1
3 1 1 ,0,1
4 2 2 ,0,1,2
5 2 2 ,0,1,2
6 3 2 ,0,1,3
7 6 3 ,0,1,3,6
8 0 0 ,0
9 8 1 ,0,8
10 8 1 ,0,8
11 8 1 ,0,8
12 9 2 ,0,8,9
13 9 2 ,0,8,9
14 12 3 ,0,8,9,12
15 12 3 ,0,8,9,12
16 15 4 ,0,8,9,12,15
17 15 4 ,0,8,9,12,15
18 3 2 ,0,1,3
19 2 2 ,0,1,2
20 6 3 ,0,1,3,6
21 8 1 ,0,8
以上就是一句sql实现mysql的递归查询的实现全过程,希望对大家的学习有所帮助。