简体   繁体   中英

SQL IN statement and ordering the results

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."')";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM