mike
mike

Reputation: 8141

MySQL WHERE IN - Ordering

When using:

SELECT * FROM some_table WHERE id IN(4,2,1,3,5);

The resulting order is:

1,2,3,4,5

What can I do to return the results in the same order I queried them in?

thanks

Upvotes: 1

Views: 541

Answers (2)

maček
maček

Reputation: 77778

SELECT *
FROM some_table
WHERE id IN(4,2,1,3,5)
ORDER BY FIELD (id, 4,2,1,3,5);

More info on MySQL FIELD() function

Upvotes: 7

D'Arcy Rittich
D'Arcy Rittich

Reputation: 171411

SELECT *
FROM some_table 
WHERE id IN (4,2,1,3,5)
order by case id
    when 4 then 1
    when 2 then 2
    when 1 then 3
    when 3 then 4
    when 5 then 5
end 

or

SELECT * FROM some_table WHERE id = 4
union all
SELECT * FROM some_table WHERE id = 2
union all
SELECT * FROM some_table WHERE id = 1
union all
SELECT * FROM some_table WHERE id = 3
union all
SELECT * FROM some_table WHERE id = 5

Upvotes: 1

Related Questions