views:

52

answers:

3

I have a column using IDs that I want to sort by. It has ID values from 1 to 3. However, instead of just using ASC of DESC, I want to do a custom sort by 2, 3, 1. How do I make this happen?

+1  A: 

You could add a virtual column with values would be

MOD(ID, 3)

and order your query ascending by it. For example:

SELECT somecolumn, MOD(ID, 3) AS ordered_id FROM my_table ORDER BY ordered_id
eKek0
This absolutely works, but it should be noted that if the table has more than 3 IDs, this query has to be altered manually (which isn't the biggest deal, but the purist in me struggles, ha!).
ABach
Hmmm... why does this work? 2/3/1 MOD 3 results in 2/0/1. Don't you need to use MOD(ID+1, 3)?
Heinzi
A: 

Untested:

SELECT ..., IF(ID=2, 1, IF(ID=3, 2, 3)) AS orderByValue
  FROM ...
 ORDER BY orderByValue

It uses the IF function to convert ID values:

 ID     orderByValue
  2        1
  3        2
else       3
Heinzi
+2  A: 

I think the easiest way is to do it like this:

SELECT * FROM `mytable` ORDER BY FIND_IN_SET(id, '2,3,1')
edwin
This is exactly what I was looking for. Thanks!
Spencer Carnage
+1, very elegant!
Heinzi