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
2010-05-08 18:28:28
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
2010-05-08 18:37:41
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
2010-05-08 18:40:48
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
2010-05-08 18:38:06
+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
2010-05-08 18:40:47