There is also a MySQL FIELD function.
If you want to do a complete sort for all possible values:
SELECT id, name, priority FROM mytable ORDER BY FIELD(name, "core", "board", "other")
If you are only concerned about the fact that the "core" is the first, and other values do not matter:
SELECT id, name, priority FROM mytable ORDER BY FIELD(name, "core") DESC
If you want to sort by "core" first, and the rest of the fields in the usual order:
SELECT id, name, priority FROM mytable ORDER BY FIELD(name, "core") DESC, priority
There are some caveats here:
Firstly, I'm sure this is only a mysql function - the question is marked as mysql, but you never know.
Secondly, pay attention to how FIELD() works: it returns values based on a single index - in the case of FIELD(priority, "core") it will return 1 if "core" is the value. If the field value is not in the list, it returns zero. This is why DESC necessary if you do not specify all possible values.
Nerdmaster Aug 21 '14 at 18:07 2014-08-21 18:07
source share