SELECT ancestor_id FROM ClosureTable WHERE descendant_id = 4;
It returns the values โโ1, 2, 4. But they are returned in separate lines, and they do not indicate that they are in the correct order (we cannot assume that the numerical order corresponds to the order of the tree hierarchy).
Sometimes you also keep depth for every path in ClosureTable . But even if not, you can calculate how many ancestors a given node has and use for sorting:
SELECT ct1.ancestor_id, COUNT(*) AS depth FROM ClosureTable ct1 JOIN ClosureTable ct2 ON (ct1.ancestor_id = ct2.descendant_id) WHERE ct1.descendant_id = 4 GROUP BY ct1.ancestor_id ORDER BY depth;
Yes, it still returns a result in three lines. If you use MySQL, you have access to GROUP_CONCAT() . Otherwise, it is easy to get three lines and combine their values โโinto application code.
source share