I have a table with data representing a tree structure, with one column indicating the row’s position in the hierarchical tree. Each level is separated with a -.
1
1-1
2
2-1
2-2
2-2-1
2-2-2
2-2-2-1
The tree is retrieved in order simply with an ORDER BY on this column. This falls down when there are more than 10 items at any level, as the column is sorted alphabetically. MySQL sorts 10 before 3.
Actual result:
1
1-10
1-3
2
Desired result:
1
1-3
1-10
2
There could be any number of levels of depth to the values.
Is it possible to sort this data numerically in MySQL?
I think your best shot is to convert the data into something that does naturally sort. If you tree structure will always have less than 99 children, you could create a function like I have below. You would just use the “GetTreeStructureSort(columnName)” in the sort function. (If you have the possibility of 3-digit numbers, you could adjust this to be more intuitive.)
This would convert these results:
into this:
I tested this with the following code: