Mysql - hierarchical recursive query

40 Views Asked by At

I have a MySQL table which is as follows:

Id Name Parent_id
1 Admin 2
2 Admin2 3
3 SuperAdmin 0
31 User1 1
32 User2 31
33 User3 32

I use mysql query:

select  id,
        username,
        parent_id 
from    (select * from products
         order by parent_id, id) products_sorted,
        (select @pv := '0') initialisation
where   find_in_set(parent_id, @pv)
and     length(@pv := concat(@pv, ',', id))

But when trying to get the entire hierarchy, starting with parent_id=0 I only get:

Id Name Parent_id
3 SuperAdmin 0
2 Admin2 3

Help fix the error. Unfortunately, it is not possible to change the id, parent_id.

Mysql v. 8.0.27

My sqlfiddle

If parent_id=0, I expect:

Id Name Parent_id
3 SuperAdmin 0
2 Admin2 3
1 Admin 2
31 User1 1
32 User2 31
33 User3 32
0

There are 0 best solutions below