Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL ORDER BY IN()

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!

like image 242
Henk Denneboom Avatar asked Aug 26 '09 05:08

Henk Denneboom


People also ask

How do I show ascending order in MySQL?

You can use the keyword ASC or DESC to get result in ascending or descending order. By default, it's the ascending order.

How do I change the order of rows in MySQL?

An "ALTER TABLE ORDER BY" statement exist in the syntaxes accepted by MySQL. According to the documentation, this syntax: - only accept *one* column, as in "ALTER TABLE t ORDER BY col;" - is used to reorder physically the rows in a table, for optimizations.


2 Answers

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) 
like image 73
Alex Martelli Avatar answered Sep 17 '22 22:09

Alex Martelli


You could use FIELD():

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

Returns the index (position) of str in the str1, str2, str3, ... list. Returns 0 if str is not found.

It's kind of an ugly hack though, so really only use it if you have no other choice. Sorting the output in your app may be better.

like image 44
deceze Avatar answered Sep 21 '22 22:09

deceze