mysql怎么实现递归查询数据

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mysql怎么实现递归查询数据相关的知识,希望对你有一定的参考价值。

参考技术A mysql> create table treeNodes
-> (
-> id int primary key,
-> nodename varchar(20),
-> pid int
-> );
Query OK, 0 rows affected (0.09 sec)
mysql> select * from treenodes;
+----+----------+------+
| id | nodename | pid |
+----+----------+------+
| 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 |
+----+----------+------+
17 rows in set (0.00 sec)

mysql查询一个表,实现递归查询

参考技术A 给你个网上写的比较好的例子:
方法一:利用函数来得到所有子节点号。
创建一个function
getChildLst,
得到一个由所有子节点号组成的字符串.
mysql>
delimiter
//
mysql>
mysql>
CREATE
FUNCTION
`getChildLst`(rootId
INT)
->
RETURNS
varchar(1000)
->
BEGIN
->
DECLARE
sTemp
VARCHAR(1000);
->
DECLARE
sTempChd
VARCHAR(1000);
->
->
SET
sTemp
=
'$';
->
SET
sTempChd
=cast(rootId
as
CHAR);
->
->
WHILE
sTempChd
is
not
null
DO
->
SET
sTemp
=
concat(sTemp,',',sTempChd);
->
SELECT
group_concat(id)
INTO
sTempChd
FROM
treeNodes
where
FIND_IN_SET(pid,sTempChd)>0;
->
END
WHILE;
->
RETURN
sTemp;
->
END
->
//
Query
OK,
0
rows
affected
(0.00
sec)
mysql>
mysql>
delimiter
;
使用我们直接利用find_in_set函数配合这个getChildlst来查找
mysql>
select
getChildLst(1);
+-----------------+
|
getChildLst(1)
|
+-----------------+
|
$,1,2,3,4,5,6,7
|
+-----------------+
1
row
in
set
(0.00
sec)
mysql>
select
*
from
treeNodes
->
where
FIND_IN_SET(id,
getChildLst(1));
+----+----------+------+
|
id
|
nodename
|
pid
|
+----+----------+------+
|
1
|
A
|
0
|
|
2
|
B
|
1
|
|
3
|
C
|
1
|
|
4
|
D
|
2
|
|
5
|
E
|
2
|
|
6
|
F
|
3
|
|
7
|
G
|
6
|
+----+----------+------+
7
rows
in
set
(0.01
sec)
mysql>
select
*
from
treeNodes
->
where
FIND_IN_SET(id,
getChildLst(3));
+----+----------+------+
|
id
|
nodename
|
pid
|
+----+----------+------+
|
3
|
C
|
1
|
|
6
|
F
|
3
|
|
7
|
G
|
6
|
+----+----------+------+
3
rows
in
set
(0.01
sec)

以上是关于mysql怎么实现递归查询数据的主要内容,如果未能解决你的问题,请参考以下文章

递归的实际业务场景之MySQL 递归查询

mysql查询一个表,实现递归查询

数据库语句的递归查询求助

mysql递归查询

mysql递归查询语句

MySQL怎样做递归查询