MySQL - SELECT ... WHERE id IN (..) - correct order

I have the following query

SELECT * FROM table WHERE id IN (5,4,3,1,6) 

and i want to retrieve the elements in the order specified in the "id in.." meaning it should return:

5 .... 4 .... 3 .... 1 .... 6 .... 

Any ideas how to do that?

3

4 Answers

Use FIELD():

SELECT * FROM table WHERE id IN (5,4,3,1,6) ORDER BY FIELD(id, 5,4,3,1,6); 
1
SELECT * FROM table WHERE id IN (5,4,3,1,6) ORDER BY FIELD (id, 5,4,3,1,6) 
0

In case anyone is still searching I just found it..

SELECT * FROM `table` WHERE `id` IN (4, 3, 1) ORDER BY FIELD(`id`, 4, 3, 1) 

And a reference for the function you can find HERE

Well your going to have to create a Id for each of the id's so:

id | otherid

1 = 5 2 = 4 3 = 3 4 = 1 6 = 6

using the IN STATEMENT only looks to see if those values are in the List, doesnt order them in any specific order

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like