1

I currently have this mysql statement:

SELECT * FROM tablename
 WHERE column1 = 'yes'
 ORDER BY
       CASE column2 WHEN 'premium' THEN 1
                    WHEN 'basic' THEN 2
                    ELSE 999
       END,
       customer_id ASC

I'd like to add another column to the mix....so here is what I would ultimately like to do.

ORDER BY:
column2 = premium
THEN
column2 = basic
THEN
column3 = specialcustomer
THEN
display remaining results according to customer_id ASC

So the output, in the order I would like it to appear.

John Doe - premium, Sally Jones - premium, Jim Smith - basic - specialcustomer, Don Johnson - basic - notspecialcustomer, Mary Lee - basic - notspecialcustomer

KTJ
  • 11
  • 2
  • KTJ: Please show a literal example of the output you want. – randomx Aug 03 '11 at 22:53
  • Hopefully, this clarifies. I have a table that has 2 levels, and then the option that a customer is special or not. I would like to first display those customers that match premium in column2, then display the customers that match basic in column2, then display the customers that match specialcustomer in column3, then display the remaining customers according to ID number – KTJ Aug 03 '11 at 23:17

1 Answers1

1
SELECT * FROM tablename
 WHERE column1 = 'yes'
 ORDER BY
       CASE column2 WHEN 'premium' THEN 1
                    WHEN 'basic' THEN 2
                    ELSE 999
       END,
       IF(column3 = 'specialcustomer', 1, 2),
       customer_id ASC

column3 = 'specialcustomer' is the check that should be returning true if specialcustomer.

What is going on in the order by section is that you can picture this like 3 additional virtual columns which get their respective value from these expressions: 1) case ... 2) if ... 3) customer_id

And then rows of the data are sorted by these column values in order.

Imre L
  • 6,159
  • 24
  • 32
  • I appreciate the time, but after the query I have a while loop, and it's now throwing an error. – KTJ Aug 04 '11 at 00:16
  • what is the error? does imre's query run fine and return the desired results? is the error a separate issue? if so, you can mark this is the answer and open a new question if needed – Derek Aug 04 '11 at 00:32
  • no, it's still not working, (the results display the same) and I am afraid I am just not getting this. With original query, there is no error, so maybe I am not understanding the IF statement. What are the 1,2 at the end? – KTJ Aug 04 '11 at 00:56
  • 1 is the value assigned for specialcustomer and 2 for all others. The rows (groups of premium,basic,other) are sorted by these values and finally by customer_id. If you do not get it, please elaborate. – Imre L Aug 04 '11 at 21:22