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
$query = "SELECT * FROM table WHERE id IN (" . $list . ") ORDER BY FIND_IN_SET(id, '".$list."')";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With