Consider this is my table structure....
id | name | parent_id
19 | category1 | 0
20 | category2 | 19
21 | category3 | 20
22 | category4 | 21
......
Now i want to fetch privious related rows with single mysql query. if i give `id=22' then query should return me id 21,20,19.
Also need to fetch (It can be a separate query) level wise data return. i.e. if i give id=22 then query should return only id 21 (first level). id 21,20 (secound level)...
Here's a similar link!
Accept answer almost going to solve my problem but it only work assending order means when parent_id < id
.
A portion of accepted answer :
select id,
name,
parent_id
from (select * from products
order by parent_id, id) products_sorted,
(select @pv := '19') initialisation
where find_in_set(parent_id, @pv)
and length(@pv := concat(@pv, ',', id))