Alphanumeric Order By in Mysql

前端 未结 4 1071
感情败类
感情败类 2020-12-20 00:29

How can i make only numeric order by when the column containing alphanumeric characters in mysql ?

column (name) is unique field.

my table contains the recor

相关标签:
4条回答
  • 2020-12-20 00:42

    I would do this way:

    select id, name from Table1 order by names + 0, names;
    

    without ordering:

    mysql> select * from alpha;
    +---+-------+
    | i | name  |
    +---+-------+
    | 1 | ab001 |
    | 2 | ab010 |
    | 3 | aa002 |
    | 4 | cc001 |
    | 5 | cb010 |
    | 6 | aaa02 |
    +---+-------+
    6 rows in set (0.00 sec)
    

    With my query:

    mysql> select i, name from alpha order by name + 0, name;
    +---+-------+
    | i | name  |
    +---+-------+
    | 3 | aa002 |
    | 6 | aaa02 |
    | 1 | ab001 |
    | 2 | ab010 |
    | 5 | cb010 |
    | 4 | cc001 |
    +---+-------+
    6 rows in set (0.00 sec)
    
    0 讨论(0)
  • 2020-12-20 00:52

    I had a slightly different issue, but the second example worked for me. I'd vote it up, but I just got started here.

    I was dealing with a single varchar column which could contain any kind of information, but it needed to sort properly no matter what was in it:

    So my column could contain info such as:

    AB CD EF GH

    or

    01 02 03 04

    The answer from Xavier caused it to be in alphabetical order when the information was all alphabetical, or numeric when the info was numeric.

    Thanks

    Thanks!

    0 讨论(0)
  • 2020-12-20 00:53

    If you have the first X characters as letters and the rest as numbers and the alpha characters vary, you are far better off changing your structure to put this data in two columns - one for the intital letters and one for the numbers. Now you don't have to do coanversions every time you want to order, you just order on the letter columns first, then the numeric column. A redesign of your structure is truly the better way to do this espcially if you wil be ordering often or if you have a large dataset.

    You could even leave the current field as the PK and have a trigger separate out to the two new fields. This way, the data is put in a format that can be ordered automatically when it is entered or updated, all current code will still work, but you can refactor to use more performant ordering.

    0 讨论(0)
  • 2020-12-20 01:02

    Assuming your strings always end with 3 digits you could use RIGHT:

    SELECT id, name
    FROM Table1
    ORDER BY RIGHT(name, 3);
    

    Result:

    1, 'ab001'
    3, 'aa002'
    8, 'ac003'
    4, 'ac004'
    7, 'aa005'
    6, 'ba006'
    2, 'ab010'
    5, 'ba015'
    

    MySQL doesn't have support for functional indexes, so this query will be relatively slow. It would be better to redesign your database (e.g. store the number separately) so that ordering on the value of a function isn't necessary.

    0 讨论(0)
提交回复
热议问题