Here a simple Table:
id, title, parent, ordering
---------------------------
3242, TitleB, 0, 1
6574, TitleBA, 3242, 1
2346, TitleBB, 3242, 2
2344, TitleA, 0, 1
7346, TitleAC, 2344, 3
3574, TitleAB, 2344, 2
2256, TitleAA, 2344, 1
1435, TitleC, 0, 1
4354, TitleCA, 1435, 1
I'm searching for a query that can order and output these rows like this:
TitleA
TitleAA
TitleAB
TitleAC
TitleB
TitleBA
TitleBB
TitleC
TitleCA
So the rows should be ordered by the first parent, then followed by its children items ordered. Then the next parent followed followed by its children items and so on.
The ordering of the parents themselves does not matter! The titles are only for better understanding and cannot be used for sorting. The important thing is that the children get sorted under their parents.
This is the last query i did:
SELECT *
FROM table t1
LEFT JOIN table t2
ON t2.id = t1.parent
ORDER BY COALESCE(t1.ordering, t2.ordering), t2.ordering