Order MySQL without using ASC or DESC

I have a column with identifiers that I want to sort. It has identifier values ​​from 1 to 3. However, instead of just using ASC DESC, I want to do a normal sort on 2, 3, 1. How can I do this?

+3
source share
3 answers

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

SELECT * FROM `mytable` ORDER BY FIND_IN_SET(id, '2,3,1')
+6
source

You can add a virtual column with values

MOD(ID, 3)

and request your ascending request. For instance:

SELECT somecolumn, MOD(ID, 3) AS ordered_id FROM my_table ORDER BY ordered_id
+1
source

Unverified:

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

It uses the IF function to convert identifier values:

 ID     orderByValue
  2        1
  3        2
else       3
0
source

Source: https://habr.com/ru/post/1744635/


All Articles