Yes, the title is confusing, but I will keep this simple. Imagine a photo page and on it are comments. These comments can be nested by replying to them. I need to find the correct sort order for them.
I am storing these hierarchies using a “lineage”. It is a textual, flattened value of the position of a single comment in the hierarchy. Here is a correctly sorted thread. I’m only showing the lineage column:
903
909
909-1404
1405
903 is the first comment, 909 the second. 1404 is a reply to the second comment, and finally, 1405 is the last comment, a non-reply. This is how they should be sorted. I’m struggling to reach that result though. This is what I get if I simply do this:
ORDER BY lineage
1405
903
909
909-1404
The error here is that 1405 should be at the bottom. I know of the (+0) trick to order text like it is a number:
ORDER BY (lineage+0)
Which gives me this:
903
909-1404
909
1405
This time, the threaded comment (1404) is wrongly sorted, it should come after the parent (909).
Is there an easy way to accomplish my desired sorting? The only thing I could think of is to fill comment ids with zeroes in front, but that would be an incredibly painful migration process that I desperately want to avoid.
Pad the numbers in lineage with zeros so you can properly order them as strings.
Of course for proper padding you need to know the max number you want to store there.
There are other ways to store hierarchic tree relations (parent links, nested tree sets). Your approach has some benefits for specific tasks, but, as you can see, also has its limits.