递归查询mysql

Recursive query mysql

我无法通过使用此语句的查询获取递归数据:

WITH RECURSIVE

我正在尝试获取与 table:

相关的行
id |      name     |extern|
--------------------------|
1  |  building_01  |  null
--------------------------|
2  |    floor_01   |  1
--------------------------|
3  |    zone_04    |  2
--------------------------|
4  |    zone_05    |  3

我需要获取此数据:zone_05 在哪里?

4 | zone_05    | 3
---------------|
3 | zone_04    | 2
---------------|
2 | floor_01   | 1
---------------|
1 | building_01| null
---------------|

我试图用这个语句解决它,但我只得到第一行相关的:

select  id,
    name,
    extern
    from    (select * from table) products_sorted,
    (select @pv := '4') initialisation
    where   find_in_set(id, @pv) > 0
    and     @pv := concat(@pv, ',', extern)

结果:

4 | zone_05    | 3
---------------|
3 | zone_04    | 2
---------------|

这个解决方案对我不起作用:

How to create a MySQL hierarchical recursive query

@trincot 是否可以将其更改为在 "reverse" 中工作?那么获取所有行 parents、grandparents 等?我已经使用您的第一个查询来获取后代,但我想获取祖先?以及。 – shreddish 2017 年 7 月 19 日在 14:54

如果其他人正在寻找@shreddish 提出的问题的答案,解决方案是将 p.parent_id = cte.id 更改为 p.id = cte.parent_id – 2017 年 12 月 10 日在 5:38

大张旗鼓

解决方案相关:

备选方案 1:使用递归,连接方式

我无法使用它,因为 mysql 数据库服务器版本。

这是您需要的查询;

select  id,
        name,
        extern_id 
from    (select * from places
         order by id desc, extern_id desc) places_sorted,
        (select @pv := '26') initialisation
where   find_in_set(id, @pv) > 0
and     @pv := concat(@pv, ',', extern_id)

这是 fiddle: http://sqlfiddle.com/#!9/ba5700/2

如您所见,"order by" 很重要,正如 trincot 在您提到的答案中所解释的那样