Sort Numeric & Alphanumeric Accordingly in PHP MySQL

懵懂的女人 提交于 2021-01-29 20:46:20

问题


I am using a Query which sorts like;

1
2
3A
3
4A
4

But I want to get it

1
2
3
3A
4
4A

What I am using is

SELECT * FROM `sections` ORDER BY CAST(`act` as DECIMAL) ASC

What I exactly want is First Number then Alphanumeric

3 then 3A

回答1:


Considering that you'll always have integer first and then characters in your acts column. Normally this is called Natural Sorting.

Problem Understanding:

  • Normal sorting works perfectly when we're dealing with variations of a single number i.e. 1, 1A, 1B, 1AB...
  • Due to string type, it fails when we sort between numbers which starts with same digit like 1, 10, 100....

We can sort in following manner.

  • First sort them based on their integer values.
  • Then sort them normally which mysql takes care by default.
SELECT * FROM sections
ORDER BY CAST(acts AS UNSIGNED), acts

Check corresponding fiddle. It is working for MySQL 5.5, 5.6, 5.7 & 8.0.



来源:https://stackoverflow.com/questions/64420770/sort-numeric-alphanumeric-accordingly-in-php-mysql

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