patternsqlMinor
MySQL : Conditional ORDER BY to only one column
Viewed 0 times
ordercolumnconditionalonemysqlonly
Problem
Hello and thanks for taking time to read this question.
I am using MySQL, and I want to sort results using ORDER BY to one specific column, but the results must be ordered according an specific criteria to this column. For example, to the following table, I want to
thanks in advance.
I am using MySQL, and I want to sort results using ORDER BY to one specific column, but the results must be ordered according an specific criteria to this column. For example, to the following table, I want to
ORDER BY 'group', showing first the 9,7,6 'group' items and, in the end 10,8,5 'group' items:names group
--------- ------
susanita 10
miguelito 5
mafalda 7
manolito 8
libertad 6
felipe 9
guille 8thanks in advance.
Solution
Use MySQL's
For example:
Because it relies on string searching,
find_in_set() function to do this. It is more concise but less portable than the CASE approach gbn proposed. For example:
SELECT `names`, `group`
FROM my_table
WHERE `group` IN (9,7,6,10,8,5)
ORDER BY find_in_set(`group`,'9,7,6,10,8,5');Because it relies on string searching,
find_in_set() is useful mainly for ordering on small sets of easily searchable keys, like integers.Code Snippets
SELECT `names`, `group`
FROM my_table
WHERE `group` IN (9,7,6,10,8,5)
ORDER BY find_in_set(`group`,'9,7,6,10,8,5');Context
StackExchange Database Administrators Q#5422, answer score: 5
Revisions (0)
No revisions yet.