Ok so I have a table called categories that looks like this:
id name parent_id
1 camera null
2 computer null
3 digital 1
4 gps null
5 laptop 2
I want to be able to return computer -> laptop or camera -> digital when I query id = 3 or 5.
Any ideas?
Use a self left join :
select a.name, b.name as parent_name from categories a left join categories b on a.parent_id = b.id where a.id in (3,5);Above query is valid for getting a one level of parent. If you want to traverse through the whole lineage please refer the following link. They have listed down few standard ways of traversing tree :
http://jan.kneschke.de/projects/mysql/sp/