I have a database
id | parentid | name
1 | 0 | CatOne
2 | 0 | CatTwo
3 | 0 | CatThree
4 | 1 | SubCatOne
5 | 1 | SubCatOne2
6 | 3 | SubCatThree
How I can select this cats Order By id
, parentid
? That is
CatOne 1
--SubCatOne 4
--SubCatOne2 5
CatTwo 2
CatThree 3
--SubCatThree 6
This should do it... with exception of a double dash "--" prefix to the name...
The order by FIRST case/when puts all the items that ARE the top level, or at the secondary level by the primary level's ID. So trying to use a parent * 1000 sample hack offered won't be an issue if you have over 1000 entries. The SECOND case/when will then force when the parent ID = 0 to the TOP of its grouped list and all its subsidiary entries UNDER it, but before the next parent ID.
however, if you DO want the double dash, change to
This:
Returns:
assuming your table is named cats, try this:
Updated to include when parent would have higher id compared to the children
If you were to sort by: ORDER BY parentid, id
then you would get the order you are looking for, but it wouldn't be intended or anything, like your example.
SQL is probably not the best medium for doing indented group like that. You can...but it's better done in your front end app
edit: sorry misread question, what Eric Petroelje said.
edit edit: Or select from the table, joined back to itself, (one for the Cat and one for the SubCat) and then specify the different ordering, one from each table.
You could try this. It is not exactly the format you specify but does it match what you require?
It produces the following: