问题
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