Natural Sort in MySQL

后端 未结 21 1111
南旧
南旧 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条回答
  •  梦毁少年i
    2020-11-22 02:51

    If you're using PHP you can do the the natural sort in php.

    $keys = array();
    $values = array();
    foreach ($results as $index => $row) {
       $key = $row['name'].'__'.$index; // Add the index to create an unique key.
       $keys[] = $key;
       $values[$key] = $row; 
    }
    natsort($keys);
    $sortedValues = array(); 
    foreach($keys as $index) {
      $sortedValues[] = $values[$index]; 
    }
    

    I hope MySQL will implement natural sorting in a future version, but the feature request (#1588) is open since 2003, So I wouldn't hold my breath.

提交回复
热议问题