Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

mysql ORDER BY based on IN clause

Posted on 2011-02-18
5
Medium Priority
?
258 Views
Last Modified: 2012-05-11
I want to ORDER my sql query based on the IN clause

select * from acct where acct_num in (200,100,150) order by (200,100,150)

My result is ordered by
100,150,200
I assume because acct_num is an index.

I want my resulting order to be
200,100,150
0
Comment
Question by:pmsguy
  • 3
5 Comments
 
LVL 143

Accepted Solution

by:
Guy Hengel [angelIII / a3] earned 2000 total points
ID: 34926691
you then need to write the order by like that:
select * from acct where acct_num in (200,100,150)
 order by case when acct_num = 200 then 0 when acct_num =  100 then 2 else 3 end

Open in new window

0
 

Author Comment

by:pmsguy
ID: 34926732
Is there an easier way to do this query?
The IN list will be dynamic.

0
 
LVL 143

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 34926764
not that I know of.
but if the "IN" list will be dynamic, so can be your order by?
0
 
LVL 11

Expert Comment

by:Ovid Burke
ID: 34927178
Try this:
SELECT * FROM acct WHERE acct_num IN (200,100,150) ORDER BY FIELD(acct_num,200,100,150);

Open in new window

0
 
LVL 143

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 34927230
actually, that is a good one!
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
Originally, this post was published on Monitis Blog, you can check it here . In business circles, we sometimes hear that today is the “age of the customer.” And so it is. Thanks to the enormous advances over the past few years in consumer techno…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …
Suggested Courses

885 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question