Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Select WHERE IN given order

Tags:

mysql

I have something like:

SELECT * FROM table WHERE id IN (118, 17, 113, 23, 72); 

It returns the rows ordered by ID, ascending. Is there a way to get back the rows in the order specified in the IN clause?

like image 301
kentor Avatar asked Sep 26 '10 21:09

kentor


2 Answers

You should use "ORDER BY FIELD". So, for instance:

SELECT * FROM table WHERE id IN (118,17,113,23,72)  ORDER BY FIELD(id,118,17,113,23,72) 
like image 66
nico Avatar answered Sep 19 '22 22:09

nico


Try using FIND_IN_SET:

SELECT * FROM table WHERE id IN (118,17,113,23,72)      ORDER BY FIND_IN_SET(id, '118,17,113,23,72'); 
like image 24
Brian Avatar answered Sep 20 '22 22:09

Brian