I need to properly order a string column that contains a delimited group of numbers, such as:
1
1.1
1.1.1
1.2
1.2.1
1.10
2
2.1
These numbers are used to define a tree: for instance 1
and 2
are top level nodes, and 1.1
, 1.2
, and 1.10
are immediate children of 1
. The tree can be arbitrarily deep so there is no upper bound per se on the number of periods that are in each entry (although in practice a character limit on the column will enforce this).
The problem I am having is that a standard ORDER BY
operation in SQL will list 1.10
ahead of 1.2
. This is of course expected, but unfortunately not what I want, since 10 > 2
. Is there an efficient way to get my ordering? I am using MySQL.
Note that I am not necessarily wedded to using this encoding for a tree, so if there is a different encoding that is easier to order than feel free to suggest it. However, one nice thing that this structure offers me is an easy way to recover either all the upstream parent nodes or all the downstream child nodes in one pass, which is not something that would work with a more typical row/parent_row model (as far as I know). For instance, given id 1.2.1.4.5
I know that the four ancestors are 1
, 1.2
, 1.2.1
, and 1.2.1.4
, and all children (both direct descendants and children of children) will have an id that starts with 1.2.1.4.5.
.