Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql order by issue

if i have a query like :

SELECT * FROM table  WHERE id IN (3,6,1,8,9);

this array of the ids is build in php dynamically , and the order is important to me.

$my_array =  array (3,6,1,8,9) ;

how can i sort the results by the order by which the elements appear in my array ?

its possible to do it in MYSQL query, or i must to order it after via php ?

like image 522
Haim Evgi Avatar asked Dec 13 '22 00:12

Haim Evgi


1 Answers

You can order by a value derived from a column. You can use a CASE operator to specify the order:

SELECT * FROM table
WHERE id IN (3,6,1,8,9)
ORDER BY CASE id WHEN 3 THEN 1
                 WHEN 6 THEN 2
                 WHEN 1 THEN 3
                 WHEN 8 THEN 4
                 WHEN 9 THEN 5
         END
like image 127
Mark Byers Avatar answered Dec 24 '22 04:12

Mark Byers