Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order results to match the order of values in a WHERE IN expression

Tags:

sql

mysql

Is there a way I can make mysql return results from a Member database by the order I ask it by in the WHERE command?

SELECT * 
FROM Members 
WHERE MemberID = "6" 
OR MemberId="3" 
OR MemberID="5"

Currently it will return results ordered by MemberID ASC no matter what I do. I want it to return by 6,3,5 i.e. in the order that I ask it.

like image 549
Aaron Lim Avatar asked Jul 12 '11 14:07

Aaron Lim


Video Answer


2 Answers

SELECT 
  * 
FROM 
  Members 
WHERE 
  MemberID IN ("6","3","5")
ORDER BY 
  FIELD(MemberID,"6","3","5");
like image 179
Mchl Avatar answered Oct 14 '22 13:10

Mchl


Select * from Members
WHERE MemberID = "6" or MemberId="3" or MemberID="5"
ORDER BY MemberID = "6" DESC, MemberId="3" DESC, MemberID="5" DESC;
like image 25
ADW Avatar answered Oct 14 '22 13:10

ADW