MySQL – Sort results in order by list

I needed today to sort a result set in MySQL after a list of id’s given. My original query was:

SELECT uid, pid FROM pages WHERE uid IN (15,17,21,87);

So the exact order of records i needed was 15, 17, 21, 87. But i wasn’t getting the results in this order. After digging around for a while i found the solution which is quite easy! I needed to alter my query a little bit to receive the desired order of results

SELECT uid, pid FROM pages WHERE uid IN (15,17,21,87) ORDER BY FIELD(uid, 15,17,21,81);

And voila, it works!

Share
Related posts:

Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to my feed and get articles like this delivered automatically to your feed reader.

Comments

This can be done a lot easier. Just use ORDER BY uid [DESC|ASC] (desc-> order descending, asc-> order ascending)

Leave a comment

(required)

(required)


Get Adobe Flash playerPlugin by wpburn.com wordpress themes