tags:

views:

67

answers:

4

This is my table:

CREATE TABLE t (id INT, parent INT, FOREIGN KEY(parent) REFERENCES t(id));

This is a collection of data I have:

id    parent
1     NULL
2     NULL
3     1
4     1

I would like to select them and order like this:

id    parent
1     NULL
3     1
4     1
2     NULL

I can't find a proper way to do it (in MySQL 5+). Please help, thanks!

+3  A: 

If there's only children and parents, and no grandchildren, you can use:

select  id
,       parent
from    yourtable
order by
        coalesce(parent, id)
Andomar
How does that differ from "order by parent, id"? I've never used coalesce before...
Kendrick
+1 beat me to it.
Martin Smith
colaesce(a, b) is the equivalent of (if a is null then b else a)
Mark Bannister
@Mark Thanks! @Andomar: In the above case, the order by values would be (for rows with ID 1,2,3,4 respectivly from the first dataset) 1,2,1,1. The order of the data returned would not be guaranteed that the parent would preceed the child.
Kendrick
Actually, order by coalesce(parent, id), id + coalesce(parent, 0) might be better, as I think Vincenzo wants parents to precede their own children.
Mark Bannister
@kendrick. How about `coalesce(parent, id), parent` (Do NULLs sort at the top or bottom in MySql?)
Martin Smith
In this case [IFNULL(parent, id)](http://dev.mysql.com/doc/refman/5.1/en/control-flow-functions.html#function_ifnull) could also be used - I think...
Mike
@Martin in that case you'd have (1,NULL)(1,1)(1,1)(2,NULL). Assuming 1 level of children and you don't care about the order of the children (which you could probably solve by adding a 3rd sort order on ID) then I think that would do it.
Kendrick
A: 

I believe this should do the trick

SELECT id, parent FROM t ORDER BY IF(parent is NOT NULL,parent,id)
Kristoffer S Hansen
+1  A: 

Not possible in a simple query, you have to order by 1 column at a time. I haven't tried it with MySQL. It's possible if you joined an ordered query with another ordered query you might be able to do something, but I doubt you could ever guarantee the order across DB versions or different data sets.

It's likely that the easier option would be to just deal with it in a specific order from the DB and display it in the order you want through your front end code.

Kendrick
I agree with @Kendrick, and can also add that any possible solution that comes up is only likely to work if the ordering of the parents and children is sequential. what if you have a parent which has a larger id than it's children, this may get complicated!
Dave Rix
+1  A: 
SELECT * FROM REFERENCES ORDER BY id=2, parent , id

OR JUST

SELECT * FROM REFERENCES ORDER BY id=2 , id
Salil