SQL IN expression and ordering of results

I have a comma separated list of identifiers that I want to use to retrieve records from the database. I can use the IN statement to get the results, but I want the order of the results to be in the same order as the original list.

E.G.

$list = "3,1,4,2,5"; $query = "SELECT * FROM table WHERE id IN (" . $list . ")"; $result = @mysql_query($query); while($row=mysql_fetch_array($result)){ echo($row['id']. ", " ); // returns 1, 2, 3, 4, 5 } 

OK, so I am returning the results in the order they appear in the database - fairly fairly, but I want the results to be in the same order as the original list, I want SQL to retrieve 3 first, then 1, etc. ..

Is there an SQL command for this or do I just need to arrange the result as I need it by shuffling the array? What is the best way to do this?

thanks

+4
source share
1 answer
 $query = "SELECT * FROM table WHERE id IN (" . $list . ") ORDER BY FIND_IN_SET(id, '".$list."')"; 
+9
source

Source: https://habr.com/ru/post/1305111/


All Articles