tags:

views:

34

answers:

4

I have a statement like the below. The order returned is 1,4,5. My code expects 4,5,1 because of output precedence rules. How do i make mysql return the order i specified?

select *
from Post 
where flag='0' and id in(4,5,1)
A: 

without an order by clause mysql is free to return the result in any order it wants.

you'd have to specify the ordering with order by

knittl
This is technically true but is not very helpful.
MJB
+5  A: 
select *
from Post 
where flag='0' and id in(4,5,1)
ORDER BY FIND_IN_SET(id, '4,5,1')

MySQL Doc for FIND_IN_SET

Crooy
nice! (yadayada)
knittl
Nice! it seems to give it to me in the order 1 5 4 (writing this as a note to others) but .Reverse() in .NET solves that :D
acidzombie24
@acidzombie: you could also order by find_in_set(…) desc
knittl
@knittl: Weird thing is, not only did it not do it but ASC and DESC dont get the same results in reverse order
acidzombie24
A: 

Try this instead:

SELECT * FROM Post WHERE flag='0' AND id = 4
UNION
SELECT * FROM Post WHERE flag='0' AND id = 5
UNION
SELECT * FROM Post WHERE flag='0' AND id = 1

It's horribly inefficient, but it won't require you to change your schema.

Craig Trader
... and won't solve the problem.
MJB
A: 

A possible solution:

select *
from Post 
where flag='0' and id = 4
UNION
select *
from Post 
where flag='0' and id = 5
UNION
select *
from Post 
where flag='0' and id = 1
despart
sql operates on sets, and mysql is free to return those union query in any order (although usually it returns them without reordering)
knittl
This still does not address the question.
MJB