MySQL ORDER BY IN() MySQL ORDER BY IN() php php

MySQL ORDER BY IN()


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)


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.


Standard SQL does not provide a way to do this (MySQL may, but I prefer solutions that are vendor-neutral so I can switch DBMS' at any time).

This is something you should do in post-processing after the result set is returned. SQL can only return them in an order specified in the "order by" clause (or in any order if there's no such clause).

The other possibility (though I don't like it, I'm honor-bound to give you the choice) is to make multiple trips to the database, one for each ID, and process them as they come in:

select * from tbl where article_id = 4;// Process those.select * from tbl where article_id = 7;// Process those.: : : : :select * from tbl where article_id = 9;// Process those.