Possible Duplicate:
What is the most efficient/elegant way to parse a flat table into a tree?
php / Mysql best tree structure
I have a table in my database full of groups, each group row has a parent id until the last parent id is 0, making a pyramid. For example:
id: 1
name: staff
parent: 0
id: 2
name: communications team
parent: 1
id: 3
name: web department
parent: 2
Now that can go on forever down the lines, so what I want to do is by using one sql statement giving the web department id it will pull all of the parent groups until the parent is 0.
Is that possible within an sql statement? How could I do that?
I don’t think you need a loop at all… just something like this in T-SQL:
This should return all rows where the parent id is less than or equal to the parent id of staff. If you want it ordered the other way, use ORDER BY parent ASC instead.