MySQL 'Order By' - sorting alphanumeric correctly

后端 未结 15 2355
执念已碎
执念已碎 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:55

    I know this post is closed but I think my way could help some people. So there it is :

    My dataset is very similar but is a bit more complex. It has numbers, alphanumeric data :

    1
    2
    Chair 
    3
    0
    4
    5
    -
    Table
    10
    13
    19
    Windows
    99
    102
    Dog
    

    I would like to have the '-' symbol at first, then the numbers, then the text.

    So I go like this :

    SELECT name, (name = '-') boolDash, (name = '0') boolZero, (name+0 > 0) boolNum 
    FROM table 
    ORDER BY boolDash DESC, boolZero DESC, boolNum DESC, (name+0), name
    

    The result should be something :

    -
    0    
    1
    2
    3
    4
    5
    10
    13
    99
    102
    Chair
    Dog
    Table
    Windows
    

    The whole idea is doing some simple check into the SELECT and sorting with the result.

提交回复
热议问题