How can I get a list of ordered rows from a list of ordered ids from a MySQL table?
I'm working in PHP, and I have a list of ids, which are ranked, with the first being the most important. I'm retrieving the rows using something like this (simplified for clarity):
$id_as_sql_list = implode("','", $id_list);
$sql = "SELECT * FROM books
WHERE id in ('$id_as_sql_list')";
This basically works out as:
WHERE id in ('456', '123', '789')
The problem is, the result from the database isn't coming back in the order of the l开发者_如何转开发ist. What's the best way to get them back in this order?
Take a look at order by field syntax.
This is an example
select * from table
where id in (x,y,z)
order by field(id,x,y,z)
$sql = "SELECT * FROM books
WHERE id in ('$id_as_sql_list')
ORDER BY YourRankingField ";
use ORDER BY
$sql = "SELECT * FROM books
WHERE id in ('$id_as_sql_list') ORDER BY whatever";
where whatever
is the field you wish to order by.
精彩评论