MySQL:仅对一列进行条件 ORDER BY

moo*_*onw 3 mysql order-by condition

您好,感谢您花时间阅读这个问题。

我正在使用 MySQL,并且我想使用 ORDER BY 对一个特定列对结果进行排序,但必须根据该列的特定条件对结果进行排序。例如,对于下表,我想ORDER BY 'group'首先显示9,7,6 'group' items和,最后显示10,8,5 'group' items

names     group
--------- ------
susanita  10
miguelito 5
mafalda   7
manolito  8
libertad  6
felipe    9
guille    8
Run Code Online (Sandbox Code Playgroud)

提前致谢。

Nic*_*mas 5

使用MySQL的find_in_set()函数来做到这一点。它比gbn 提出的CASE 方法更简洁,但可移植性较差。

例如

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');
Run Code Online (Sandbox Code Playgroud)

因为它依赖于字符串搜索,find_in_set()所以主要用于对一小组易于搜索的键(例如整数)进行排序。