I have this records in my table :
id | title | sub
-----+-------------+------
1 | Parent 1 | 0
2 | Parent 2 | 0
3 | Sub 1-1 | 1
4 | Parent 3 | 0
5 | Sub 1-2 | 1
6 | Sub 2-1 | 2
7 | Parent 4 | 0
Now I want select this records from my table with one query like this :
id | title | sub
-----+-------------+------
1 | Parent 1 | 0
3 | Sub 1-1 | 1
5 | Sub 1-2 | 1
2 | Parent 2 | 0
6 | Sub 2-1 | 2
4 | Parent 3 | 0
7 | Parent 4 | 0
I want to sort my records by Parent and then childs.
How can I do this in mySQL ?
UPDATE:
I use this query :
SELECT a.*,
CASE WHEN SUB = 0 THEN ID ELSE SUB END expression
FROM category a
ORDER BY CASE WHEN SUB = 0 THEN ID ELSE SUB END, ID
And my data is :
id | title | sub
----+---------------+-------
1 | Parent 1 | 0
2 | Parent 2 | 0
3 | Sub 1-1 | 7
4 | Parent 3 | 0
5 | Sub 1-2 | 4
6 | Sub 2-1 | 2
7 | Parent 4 | 0
The result is :
id | title | sub | expression
----+-----------+-------+-----------
1 | Parent 1 | 0 | 1
2 | Parent 2 | 0 | 2
6 | Sub 2-1 | 2 | 2
4 | Parent 3 | 0 | 4
5 | Sub 1-2 | 4 | 4
3 | Sub 1-1 | 7 | 7
7 | Parent 4 | 0 | 7
If there wouldn’t be more than 1 level, you could make an expression with
CASEon your order by clause:With that expression, it will always order by the parentId, which is the
SUBcolumn when populated or theIDcolumn when it is not a child.Would result:
It would still fail if any of the Child could be a parent of another record (Sub 1-2-1 for example).