I am trying to fetch all the children of given id on mysql version 5.7.37
id | name | parent_id |
---|---|---|
1 | post1 | 0 |
2 | post2 | 1 |
3 | post3 | 6 |
4 | post4 | 6 |
5 | post5 | 6 |
6 | post6 | 0 |
this solution works but it is for newer versions of mysql
with recursive cte (id, name, parent_id) as (
select id,
name,
parent_id
from posts
where parent_id = 6
union all
select p.id,
p.name,
p.parent_id
from posts p
inner join cte
on p.parent_id = cte.id
)
select * from cte;
this solution have a bug in it and it wont work if you are trying to fetch id 6 from given table
select * from (select * from posts) posts, (select @pv := 6) initialisation where (find_in_set(parent_id, @pv) > 0 and @pv := concat(@pv, ',', id)) OR id = 6
i can use stored procedure or functions also. Please suggest the solution.