1

I have a following table:

+----+-----------+------+
| id | parent_id | name |
+----+-----------+------+
|  1 | 4         | d    |
|  2 | null      | a    |
|  3 | 2         | b    |
|  4 | null      | c    |
+----+-----------+------+

parent_id points to a record in the same table. If parent_id is null it a root element.

Data can be in random order. Is it possible to order my select so the output will be in the order they would be in an expanded tree: A, B, C, D?

Or is it better to select it in random order and order it programmatically by iterating the result, finding the first root element and then iterating the whole result again to find all the children for that element and etc?

Bill Karwin
  • 538,548
  • 86
  • 673
  • 828
user1985273
  • 1,817
  • 15
  • 50
  • 85
  • What is your actual use case? This does not sound like something mysql is very good at. – Emile Pels Jan 21 '18 at 17:00
  • i want to display them to the user in order where first i display a root element, then all its children, then the next root, etc. Guess ill do it programmatically at the moment. – user1985273 Jan 21 '18 at 17:11

0 Answers0