I have a tree in my database that is stored using parent id links.
A sample of what I have for data in the table is:
id | name | parent id ---+-------------+----------- 0 | root | NULL 1 | Node 1 | 0 2 | Node 2 | 0 3 | Node 1.1 | 1 4 | Node 1.1.1 | 3 5 | Node 1.1.2 | 3
Now I would like to get a list of all the direct descendants of a given node but if none exist I would like to have it just return the node itself.
I want the return for the query for children of id = 3 to be:
children -------- 4 5
Then the query for the children of id = 4 to be:
children -------- 4
I can change the way I am storing the tree to a nested set but I don’t see how that would make the query I want possible.
In new
PostgreSQL 8.4you can do it with aCTE:See this article in my blog for details:
PostgreSQL 8.4: preserving order for hierarchical queryIn
8.3or earlier, you’ll have to write a function:and select from this function:
The first parameter is the root
id, the second should be1.See this article in my blog for more detail:
PostgreSQLUpdate:
To show only the first level children, or the node itself if the children do not exist, issue this query:
This is more efficient than a
JOIN, since the second query will take but two index scans at most: the first one to make sure to find out if a child exists, the second one to select the parent row if no children exist.