Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL IN statement and ordering the results

Tags:

arrays

php

mysql

I have a comma delimited list of ids 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 the same order as the original list.

EG

$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 get the results back in the order that they appear in the database - fair enough 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 a SQL command to do this or do I just need to arrange the result the way I need it by some array shuffling? What is the best way to do this?

thanks

like image 209
undefined Avatar asked Jan 22 '23 09:01

undefined


1 Answers

$query = "SELECT * FROM table WHERE id IN (" . $list . ") ORDER BY FIND_IN_SET(id, '".$list."')";
like image 170
reko_t Avatar answered Feb 01 '23 02:02

reko_t