I asked this question previously but this was for a two-layer tree and the solution I was given worked perfectly.
I now have a multi level tree (up to 3, but lets assume there could be more in the future.
My code currently looks like this:
SELECT * FROM fin_document AS finl
LEFT OUTER JOIN fin_document AS finl2
ON finl2.id = finl.parent_line_id
ORDER BY
CASE WHEN finl2.ordinal IS NULL THEN finl.ordinal
ELSE concat(finl2.ordinal,'-',finl.ordinal) END
Lets assume a similar tree as before:
(id) (Item) (#) (parent_line_id)
1234 - Car - 1 - null
0000 - Boat - 2 - null
2222 - House - 4 - null
6545 - Bike - 5 - null
6547 - Wheels - 0 - 1234
4442 - Bed - 1 - 2222
1474 - Sink - 0 - 2222
9456 - Tires - 0 - 6547 *New item, child of wheels
8975 - L.Nuts - 1 - 6547 *New item, child of wheels
oh and the # column is "ordinal"
So how would I get this to sort proper with more than one parent?
The proper sort should look like:
(id) (Item) (#) (parent_line_id)
1234 - Car - 1 - null
6547 - Wheels - 0 - 1234
9456 - Tires - 0 - 6547
8975 - L.Nuts - 1 - 6547
0000 - Boat - 2 - null
2222 - House - 4 - null
1474 - Sink - 0 - 2222
4442 - Bed - 1 - 2222
6545 - Bike - 5 - null
Note: I cannot alter the tables whatsoever. I am only able to pull data from the tables, as the tables are managed by another company, who's software we use. I'm aware that they will get more and more complex if there are more children, but I do not think there will be more than 3-4 children for what my company will be using this for. Unfortunately, due to this complexity, this is why I had to return here and ask again :(


Hopefully you aren't looking for something that is going to work with N deep hierarchy without modification.
This should be fairly trivial to extend, however.
demo here
The basic premise is we identify all the parentless items, and give them a parentage of 1.
We then identify their children, give them a parentage of 2, and their children get a parentage of 3.
All of them inherit the first parents ordinal for sorting purposes, then.
There are probably other ways to do this, i'm probably even going to look for them, but in the mean time - this works.