Natural Sort in MySQL

后端 未结 21 1088
南旧
南旧 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 02:51

    I know this topic is ancient but I think I've found a way to do this:

    SELECT * FROM `table` ORDER BY 
    CONCAT(
      GREATEST(
        LOCATE('1', name),
        LOCATE('2', name),
        LOCATE('3', name),
        LOCATE('4', name),
        LOCATE('5', name),
        LOCATE('6', name),
        LOCATE('7', name),
        LOCATE('8', name),
        LOCATE('9', name)
       ),
       name
    ) ASC
    

    Scrap that, it sorted the following set incorrectly (It's useless lol):

    Final Fantasy 1 Final Fantasy 2 Final Fantasy 5 Final Fantasy 7 Final Fantasy 7: Advent Children Final Fantasy 12 Final Fantasy 112 FF1 FF2

提交回复
热议问题