I have the following table on a PostgreSQL database (parent_fk is a foreign key that references the same table):
id | parent_fk
72 |
342 | 72
583 | 342
I want to query this table and discover the path of each element to the ultimate parent via intermediate parent/child relationships. For example, I would like to obtain the following as the answer to an SQL query:
id | parent_fk | path
72 | | 72
342 | 72 | 72;342
583 | 342 | 72;342;583
I read about CTE (Common Table Expressions) and recursive queries on PostgreSQL but I couldn’t solve this problem by myself yet. Any ideas? Thanks in advance.
You may want to examine the
ltreecontrib module if you’re doing much of this sort of thing.Here’s a CTE that’ll do the job, see SQLFiddle:
Your table is a representation of a directed graph as a set of edges. You’ve specified that the graph is a tree, meaning that it’s acyclic. What you want to do is to find the path from each node (inner or leaf) on the tree to the root and represent that as a semi-colon separated string.