Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

issue with ORDERING query results

Tags:

php

mysql

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.

like image 401
Joe Avatar asked Feb 24 '23 06:02

Joe


1 Answers

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.

like image 87
Nicola Cossu Avatar answered Feb 26 '23 20:02

Nicola Cossu