issue with ORDERING query results
I currently construct an array of ids and query this array using implode 开发者_运维知识库like so:
$sql = "SELECT * FROM item_bank_tb WHERE item_id IN(" . implode(',', $ids) . ")";
the array $ids
is constructed in such a way that the ids are in a specific order. However the results of this query are not in that order. I'm guessing as they are all in one query the results appear in the order they were located (ascending).
Is there a way of getting around this? (other than including a field which i can ORDER BY)
many thanks.
Take a look at this example. You have to use field() function.
SELECT * FROM item_bank_tb WHERE item_id IN(1,3,2)
order by field(item_id,1,3,2)
in this way you can get your items in your desired order.
Seriously, what's the problem with adding ORDER BY item_id
If you want the rows of a SQL query returned in a specific order, you must include an ORDER BY
in the query.
Use ORDER BY
to sort your results. You can either have ORDER BY DESC
(descending values from higher to lower) or ORDER BY ASC
(ascending from lower to higher).
For example:
SELECT colName,colEmail FROM tblUsers ORDER BY id ASC
Read more here:
http://www.w3schools.com/sql/sql_orderby.asp
you can construct an "orderer" temporay table (if it has not too much data) instead of the id array you can insert to the temp table two values: ID, order
and then join and then query with "order by order"
精彩评论