Imran Hussain
Imran Hussain

Reputation: 25

Order MySQL query by multiple ids

I have problems sorting results from MySQL. Here is the code:

$my_query = "
SELECT * 
FROM tbl1, tbl2, tbl3 
WHERE tbl1.id = tbl2.id2 
  AND tbl1.sub_id = tbl3.sub_id 
  AND tbl1.id IN(22, 55, 5, 10, 40, 2001, 187)
";

This query works fine, but when I print it, it's ordered by tbl1.id ASC. I want to display the same order as I used in IN(22,55,5,10,40,2001,187).

I think it is possible, but I tried my best and did not get it fixed. Is there any solution that works for me?

Upvotes: 2

Views: 1347

Answers (1)

Mark Byers
Mark Byers

Reputation: 839234

Add this ORDER BY clause that uses the FIELD function to get the order you want:

ORDER BY FIELD(tbl1.id, 22, 55, 5, 10, 40, 2001, 187)

Upvotes: 5

Related Questions