Return MySQL Results from an “IN” Query in the Correct Order
By marc • Apr 29th, 2008 • Category: MySQLThe scenario:
You have a list of ids in a particular order that you want to search for in a MySQL table. Perhaps the ids were returned in this order from a search index or something else. Whatever the case is, now you want to get the results in the same order as the ids that you supplied. However, you discover that MySQL actually returns the results in a different order. How exactly do you get it to order by the supplied list?
Let take an array of ids in a desired order:
4, 9, 1, 5
And our example query:
-
-
SELECT * FROM characters WHERE id IN (4, 9, 1, 5)
Desired Result:
-
-
ID NAME
-
=================================
-
4 Marty McFly
-
9 Dr. Emmett Brown
-
1 George McFly
-
5 Einstein
Actual Returned Result:
-
-
ID NAME
-
=================================
-
1 George McFly
-
4 Marty McFly
-
5 Einstein
-
9 Dr. Emmett Brown
As we can see, MySQL actually orders the results by the id, so we need to force it to order everything by our original list of ids. The secret is using an ORDER BY CASE syntax in the query. Here’s an example:
Revised Query:
-
-
SELECT *
-
FROM characters
-
ORDER BY CASE id
-
WHEN 4 THEN 1
-
WHEN 9 THEN 2
-
WHEN 1 THEN 3
-
WHEN 5 THEN 4
-
ELSE 999
-
END
By using the “ORDER BY CASE”, we are specifying what positions each of the returned results should appear in.
PHP Example
Here is an example of how you can create the query within PHP.
-
-
// create our array of ids to search for
-
$search_ids = array(4, 9, 1, 5);
-
-
// create the case variable for query
-
$case = '';
-
-
// loop through the search array
-
foreach ($search_ids as $key => $value){
-
-
// create our place number
-
$num = $key + 1;
-
-
// add the id to the case string
-
$case .= " WHEN $value THEN $num ";
-
-
}
-
-
// convert ids to string
-
$ids = implode(',', $ids);
-
-
// build the final query
-
$sql = "SELECT *
-
FROM characters
-
WHERE
-
id IN ($ids)
-
ORDER BY
-
CASE id
-
$case
-
ELSE 999
-
END
-
";
-
-
// run the query….