user34537
user34537

Reputation:

MySql in array order?

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)

Upvotes: 8

Views: 5056

Answers (5)

Ivan
Ivan

Reputation: 61

Try a more explicit ordering: ORDER BY FIELD(id,4,5,1);

Upvotes: 6

Crooy
Crooy

Reputation: 176

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

Upvotes: 14

David Espart
David Espart

Reputation: 11790

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

Upvotes: 0

Craig Trader
Craig Trader

Reputation: 15699

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.

Upvotes: 0

knittl
knittl

Reputation: 265966

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

Upvotes: 0

Related Questions