在使用MySQL的排序时,可能需要根据某个字段取值的特定顺序来进行排序。此时,我们就可以使用ORDER BY FIELD。
以fruit表为例,fruit表的“name”字段用于保存各个fruit的名字:Apple, Banana, Orange, Pear.
现在,我们要对fruit中查询的结果进行排序,希望结果按照:Banana, Orange, Pear, Orange 的顺序排列。就可以使用 ORDER BY FIELD来操作。
SELECT * FROM fruit
ORDER BY FIELD(name, 'Banana', 'Apple', 'Pear', 'Orange'), variety;
查询结果如下:
+----------+--------+---------------------+
| fruit_id | name | variety |
+----------+--------+---------------------+
| 11 | Banana | Burro |
| 12 | Banana | Cavendish |
| 10 | Banana | Plantain |
| 6 | Apple | Cox's Orange Pippin |
| 7 | Apple | Granny Smith |
| 1 | Apple | Red Delicious |
| 8 | Pear | Anjou |
| 4 | Pear | Bartlett |
| 2 | Pear | Comice |
| 5 | Orange | Blood |
| 3 | Orange | Navel |
| 9 | Orange | Valencia |
+----------+--------+---------------------+
参考:http://www.electrictoolbox.com/mysql-order-specific-field-values/