Order column by certain criteria in mysql

ぃ、小莉子 提交于 2019-12-25 02:19:25

问题


I need to be able to order my output data in a proper way using MySQL. I'm using ORDER BY so far and everything was working correctly until now.

Let's say I have something like this: Table VEHICLES:

ID | Name | MainGroup | SubGroup 
1  |  A   |   Vehicle |   Truck
2  |  B   |   Vehicle |   Car
3  |  C   |   Vehicle |   Car
4  |  D   |   Vehicle |   Truck
5  |  E   |   Vehicle |   Truck
6  |  F   |   Vehicle |   Motorbike

I was using this:

SELECT * FROM Vehicles WHERE MainGroup=Vehicle ORDER BY Subgroup;

When I get selections they are not sorted in a way that I want, because now I want to be able to determine the way of the selected ones. Let's say that I want an output like this Car, Truck, Motorbike or some other way around. How to achieve this? Is this doable using an order by?


回答1:


Use field():

SELECT *
FROM Vehicles
WHERE MainGroup=Vehicle
ORDER BY field(Subgroup, 'Car', 'Truck', 'Motorbike');


来源:https://stackoverflow.com/questions/23325200/order-column-by-certain-criteria-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!