MySQL ORDER BY [custom SET field value]

…衆ロ難τιáo~ 提交于 2019-12-18 04:24:16

问题


I hope there's a simple solution for this:

I have a table where each row has it's own status (SET type field). Statuses can be:

  • offline
  • available
  • busy
  • distance

I'd like to order as follows

  • available
  • busy
  • distance
  • offline

I thought a simple

ORDER BY `status` ASC

will do the trick (alphabetical order) but it gives me the following:

  • offline
  • available
  • busy
  • distance

How can is sort out this in the most simple way?

Thanks in advance,

fabrik


回答1:


Thought I'd add another way to order by custom field values,

ORDER BY FIND_IN_SET(status, 'available,busy,distance,offline')

(If the given strings contain a quote simply escape it)




回答2:


SELECT * FROM table ORDER BY FIELD(status,'offline','available','busy','distance')

see Mysql order by specific ID values




回答3:


You could also do something like this, if reordering the SET values in impractical:

... ORDER BY CASE `status` 
                WHEN 'available' THEN 1
                WHEN 'busy' THEN 2
                WHEN 'distance' THEN 3
                WHEN 'offline' THEN 4
             END



回答4:


Simpler than the solutions above:

ORDER BY CONCAT(status)



回答5:


Nevermind.

The trick is saving SET values at the right order.



来源:https://stackoverflow.com/questions/4025675/mysql-order-by-custom-set-field-value

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