Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Order By Help!

I am looking to do an order by in a certain order. I know I can modify the entire database but I would then need to modify the entire code base.

What I am have, is a column in a table 'games' called 'status'.

So...

  SELECT * 
    FROM games 
ORDER BY status ASC  -- Will retrieve results going from 0 then 1 then 2

What I am looking for is to be able to order it by 1 then 0 then 2.

Any ideas???

like image 845
Jeffrey Hunter Avatar asked Nov 07 '10 02:11

Jeffrey Hunter


1 Answers

If I understand correctly, using a CASE expression:

  SELECT g.* 
    FROM GAMES g
ORDER BY CASE g.status 
           WHEN 0 THEN 1
           WHEN 1 THEN 2
           WHEN 2 THEN 3
         END

Using FIND_IN_SET function:

  SELECT g.* 
    FROM GAMES g
ORDER BY FIND_IN_SET(g.status, '0,1,2')

Using FIELD function:

  SELECT g.* 
    FROM GAMES g
ORDER BY FIELD(g.status, 0, 1, 2)
like image 102
OMG Ponies Avatar answered Sep 28 '22 03:09

OMG Ponies