Sort MySQL results alphabetically, but with numbers last

淺唱寂寞╮ 提交于 2019-11-27 06:14:31

问题


Often, sorting is done with symbols sorted to the top, like 0 or * or &. This is the default way that mysql sorts; numbers and symbols and then A-Z. However, that makes the often ugliest or most badly formatted results float to the top (e.g. a result of @#$@3423 or 8 inch or &amp).

So I'd like to do a modified form of that, letters first A-Z, and then special characters last.

How would I go about creating that type of sort? Something in the ORDER BY clause?


回答1:


Based on a google-cached link to this page: http://www.google.com/url?sa=t&source=web&cd=3&ved=0CCUQFjAC&url=http%3A%2F%2Fblog.feedmarker.com%2F2006%2F02%2F01%2Fhow-to-do-natural-alpha-numeric-sort-in-mysql%2F&ei=Zg2_TZyKDaffiALjjqwo&usg=AFQjCNGS-rX7AmfrumXK8J7bVSj96bSSmQ

EDIT: Original link is dead. Here is another link which actually explains what is happening better than the first link did:

http://matthewturland.com/2008/11/05/natural-ordering-in-mysql/

You might try this

SELECT names FROM your_table ORDER BY names + 0 ASC



回答2:


Select ...
From ...
Order By Case When Col Like '[0-9]%' Then 1 Else 0 End Asc
    , Col

Another solution that would account for special characters:

Select ...
From ...
Order By Case When Col Like '[A-Z]%' Then 0 Else 1 End Asc
    , Col



回答3:


This works for me:

SELECT * FROM `yourTable` ORDER BY `yourDatabase`.`yourColumn`  ASC


来源:https://stackoverflow.com/questions/5861852/sort-mysql-results-alphabetically-but-with-numbers-last

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