Natural Sort in MySQL

后端 未结 21 1079
南旧
南旧 2020-11-22 02:25

Is there an elegant way to have performant, natural sorting in a MySQL database?

For example if I have this data set:

  • Final Fantasy
  • Final Fant
21条回答
  •  爱一瞬间的悲伤
    2020-11-22 03:06

    You can also create in a dynamic way the "sort column" :

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

    That way, you can create groups to sort.

    In my query, I wanted the '-' in front of everything, then the numbers, then the text. Which could result in something like :

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

    That way you don't have to maintain the sort column in the correct order as you add data. You can also change your sort order depending on what you need.

提交回复
热议问题