我有一个递归表来指示监督的关系,一个人可以监督许多人,并得到其他许多人的监督。
以下是示例数据:
+--------+------------+ | person | supervises | +--------+------------+ | 1 | 2 | | 1 | 3 | | 1 | 4 | | 3 | 5 | | 4 | 5 | | 5 | 8 | | 4 | 6 | | 4 | 7 | | 6 | 9 | | 7 | 9 | | 9 | 10 | | 10 | 11 | | 3 | 11 | +--------+------------+
我的问题是,创建一个MariaDb(10.4.1)/ Mysql查询,该查询返回包含路径的行,在这种情况下,返回包含键的行,例如:1、4、6、9、10、11或1 4、7、9、10、11
select.... +------+ | path | +------+ | 1 | | 4 | | 6 | | 9 | | 10 | | 11 | +------+
答案 0 :(得分:0)
这将返回所有可能的路径和深度:
with recursive rcte as (
select person, supervises,
concat(person, ',', supervises) as path,
1 as depth
from graph
union all
select r.person, g.supervises,
concat(r.path, ',', g.supervises),
r.depth + 1
from graph g
join rcte r on r.supervises = g.person
)
select *
from rcte
order by person, supervises
结果:
person | supervises | path | depth
-------|------------|---------------|------
1 | 2 | 1,2 | 1
1 | 3 | 1,3 | 1
1 | 4 | 1,4 | 1
1 | 5 | 1,3,5 | 2
1 | 5 | 1,4,5 | 2
1 | 6 | 1,4,6 | 2
1 | 7 | 1,4,7 | 2
1 | 8 | 1,4,5,8 | 3
1 | 8 | 1,3,5,8 | 3
1 | 9 | 1,4,6,9 | 3
1 | 9 | 1,4,7,9 | 3
1 | 10 | 1,4,7,9,10 | 4
1 | 10 | 1,4,6,9,10 | 4
1 | 11 | 1,4,6,9,10,11 | 5
1 | 11 | 1,3,11 | 2
1 | 11 | 1,4,7,9,10,11 | 5
3 | 5 | 3,5 | 1
3 | 8 | 3,5,8 | 2
3 | 11 | 3,11 | 1
4 | 5 | 4,5 | 1
4 | 6 | 4,6 | 1
4 | 7 | 4,7 | 1
4 | 8 | 4,5,8 | 2
4 | 9 | 4,6,9 | 2
4 | 9 | 4,7,9 | 2
4 | 10 | 4,6,9,10 | 3
4 | 10 | 4,7,9,10 | 3
4 | 11 | 4,6,9,10,11 | 4
4 | 11 | 4,7,9,10,11 | 4
5 | 8 | 5,8 | 1
6 | 9 | 6,9 | 1
6 | 10 | 6,9,10 | 2
6 | 11 | 6,9,10,11 | 3
7 | 9 | 7,9 | 1
7 | 10 | 7,9,10 | 2
7 | 11 | 7,9,10,11 | 3
9 | 10 | 9,10 | 1
9 | 11 | 9,10,11 | 2
10 | 11 | 10,11 | 1
要获得最大深度,只需使用
select max(depth) from rcte