MySQL 'Order By' - sorting alphanumeric correctly

后端 未结 15 2109
执念已碎
执念已碎 2020-11-22 12:02

I want to sort the following data items in the order they are presented below (numbers 1-12):

1
2
3
4
5
6
7
8
9
10
11
12

However, my query - using

相关标签:
15条回答
  • 2020-11-22 12:30

    This is a simple example.

    SELECT HEX(some_col) h        
    FROM some_table 
    ORDER BY h
    
    0 讨论(0)
  • 2020-11-22 12:34

    This type of question has been asked previously.

    The type of sorting you are talking about is called "Natural Sorting". The data on which you want to do sort is alphanumeric. It would be better to create a new column for sorting.

    For further help check natural-sort-in-mysql

    0 讨论(0)
  • 2020-11-22 12:35
    SELECT length(actual_project_name),actual_project_name,
    SUBSTRING_INDEX(actual_project_name,'-',1) as aaaaaa,
    SUBSTRING_INDEX(actual_project_name, '-', -1) as actual_project_number,
    concat(SUBSTRING_INDEX(actual_project_name,'-',1),SUBSTRING_INDEX(actual_project_name, '-', -1)) as a
    FROM ctts.test22 
    order by 
    SUBSTRING_INDEX(actual_project_name,'-',1) asc,cast(SUBSTRING_INDEX(actual_project_name, '-', -1) as unsigned) asc
    
    0 讨论(0)
  • 2020-11-22 12:36

    SELECT s.id, s.name, LENGTH(s.name) len, ASCII(s.name) ASCCCI FROM table_name s ORDER BY ASCCCI,len,NAME ASC;

    0 讨论(0)
  • 2020-11-22 12:37

    This should sort alphanumeric field like: 1/ Number only, order by 1,2,3,4,5,6,7,8,9,10,11 etc... 2/ Then field with text like: 1foo, 2bar, aaa11aa, aaa22aa, b5452 etc...

    SELECT  MyField
    FROM MyTable
    order by 
        IF( MyField REGEXP '^-?[0-9]+$' = 0, 
        9999999999 ,  
        CAST(MyField AS DECIMAL) 
        ), MyField
    

    The query check if the data is a number, if not put it to 9999999999 , then order first on this column, then order on data with text

    Good luck!

    0 讨论(0)
  • 2020-11-22 12:40

    This works for type of data: Data1, Data2, Data3 ......,Data21. Means "Data" String is common in all rows.

    For ORDER BY ASC it will sort perfectly, For ORDER BY DESC not suitable.

    SELECT * FROM table_name ORDER BY LENGTH(column_name), column_name ASC;
    
    0 讨论(0)
提交回复
热议问题