Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order row selection by multiple columns

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
like image 571
Isis Avatar asked Feb 21 '11 15:02

Isis


4 Answers

assuming your table is named cats, try this:

select * from  cats
order by
      case when parentid = 0 then id else parentid end,
      case when parentid = 0 then 0 else id end

Updated to include when parent would have higher id compared to the children

like image 186
Kris Ivanov Avatar answered Sep 23 '22 08:09

Kris Ivanov


This should do it... with exception of a double dash "--" prefix to the name...

SELECT 
      t1.name,
      t1.id
   FROM 
      Table1 t1
   ORDER BY 
      case when t1.parentID = 0 then t1.ID else t1.ParentID end,
      case when t1.parentID = 0 then '1' else '2' end,
      t1.id

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

SELECT 
      if( t1.ParentID = 0, '', '--' ) + t1.name name,
     <rest of query is the same>
like image 24
DRapp Avatar answered Sep 22 '22 08:09

DRapp


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.

like image 33
Tom Morgan Avatar answered Sep 23 '22 08:09

Tom Morgan


This:

select id as parentId,
0 as sortOrder,
id,
name
from cats 
where parentId = 0
union all
select parentId,
1 as sortOrder,
id,
name
from cats 
where parentId > 0
order by parentId, sortOrder, name

Returns:

ParentId sortOrder  id   Name
    1       0       1   CatOne
    1       1       4   SubCatOne
    1       1       5   SubCatOne2
    2       0       2   CatTwo
    3       0       3   CatThree
    3       1       6   SubCatThree
like image 39
JBrooks Avatar answered Sep 24 '22 08:09

JBrooks