Solved

mysql ORDER BY based on IN clause

Posted on 2011-02-18
5
251 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 142

Accepted Solution

by:
Guy Hengel [angelIII / a3] earned 500 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 142

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 142

Expert Comment

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

Featured Post

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

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

Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

815 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

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now