41

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 on how to do that?

Montaro
  • 9,240
  • 6
  • 29
  • 30
Ciprian Mocanu
  • 2,166
  • 3
  • 25
  • 44

4 Answers4

82

Use FIELD():

SELECT * FROM table WHERE id IN (5,4,3,1,6) ORDER BY FIELD(id, 5,4,3,1,6);
Frank Heikens
  • 117,544
  • 24
  • 142
  • 135
26
SELECT * FROM table WHERE id IN (5,4,3,1,6) ORDER BY FIELD (id, 5,4,3,1,6)
delphist
  • 4,409
  • 1
  • 22
  • 22
2

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

Ciprian Mocanu
  • 2,166
  • 3
  • 25
  • 44
-1

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

Robbie Tapping
  • 2,516
  • 1
  • 17
  • 18