MySQL ORDER BY IN()

Henk Denneboom picture Henk Denneboom · Aug 26, 2009 · Viewed 42.7k times · Source

I have a PHP array with numbers of ID's in it. These numbers are already ordered.

Now i would like to get my result via the IN() method, to get all of the ID's.

However, these ID's should be ordered like in the IN method.

For example:

IN(4,7,3,8,9)  

Should give a result like:

4 - Article 4  
7 - Article 7  
3 - Article 3  
8 - Article 8  
9 - Article 9

Any suggestions? Maybe there is a function to do this?

Thanks!

Answer

Alex Martelli picture Alex Martelli · Aug 26, 2009

I think you may be looking for function FIELD -- while normally thought of as a string function, it works fine for numbers, too!

ORDER BY FIELD(field_name, 3,2,5,7,8,1)