Consider The following Table
+--------+-------+--+
| Parent | Child | |
+--------+-------+--+
| 1 | 2 | |
| 10 | 13 | |
| 2 | 3 | |
| 3 | 4 | |
| 13 | 14 | |
| 4 | 5 | |
| 15 | 16 | |
| 5 | 1 | |
+--------+-------+--+
In this table I'm following the hierarchy of parent child. From this table I want a result as the below table
+--------+-------+--+
| Parent | Child | |
+--------+-------+--+
| 1 | 2 | |
| 2 | 3 | |
| 3 | 4 | |
| 4 | 5 | |
| 5 | 1 | |
+--------+-------+--+
I want to get the hierarchy in my code (1-2-3-4-5-1). At present I'm querying for each child after getting its parent (Sometimes, Child can be any of previous Parents like 5-1). For a long hierarchy it will execute a number of queries. How can I make this more efficient?