How to sort rows by ON, OFF, SOLD

房东的猫 提交于 2019-12-11 08:34:25

问题


I have followings 3 values that could be in a row in database - ON, OFF, SOLD (column sort_it). When I set the sort clausule on ORDER BY sort_it ASC, so I will get the items with a value in the sort_in column OF, then ON and SOLD. But I need the sequence ON, OFF, SOLD.

Exist any way to do it somehow? I mean... edit a way saving data into database will be demanding, so I would do this in the last moment.


回答1:


Yes you can use custom data sortings like this:

SELECT * FROM table ORDER BY FIELD(`sort_it`,'ON','OFF','SOLD'),`sort_it`



回答2:


You can use a CASE statement to generate your custom ordering sequence from the underlying values, something like this:

ORDER BY
    CASE sort_it
        WHEN 'ON'   then 1
        WHEN 'OFF'  then 2
        WHEN 'SOLD' then 3
    END

Sample Demo: http://sqlize.com/MGz6lLb0Qk




回答3:


Using Strings is generally a bad idea. it would be better to use a numeric type. Then you can say ON=1, OFF=2 and SOLD=3 and then sort.




回答4:


SELECT t.*, IF(sort_it='ON',1,IF(sort_it='OFF',2,3)) as new_sort FROM Table AS t ORDER by new_sort ASC

Another solution from comments on MySql manual:

http://dev.mysql.com/doc/refman/5.0/en/sorting-rows.html

select * from tablename order by priority='High' DESC, priority='Medium' DESC, priority='Low" DESC;


来源:https://stackoverflow.com/questions/8064459/how-to-sort-rows-by-on-off-sold

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