1

I have having trouble performing natural sort in mysql. I am a mysql noob and maybe this is adding to the problem

I have a list of buses numbers at a website I work on

List was at first random

bus_name

F1
F22
F10
F15
F7
F90

I attempted to do a natural sort using this

mysql> SELECT version
-> FROM version_sorting
-> ORDER BY CAST(version AS UNSIGNED), version;

taken from http://www.mpopp.net/2006/06/sorting-of-numeric-values-mixed-with-alphanumeric-values/

However I have the following now

F1
F10
F15
F22
F7
F90

As I note I believe the issue above has something to do with an imaginary zero that mysql attaches with each string , thereby making F7 as F70 which is > F22

I would want my list to be like

F1
F7
F10
F15
F22
F90

Can you people help me here please

Saharsh Shah
  • 28,687
  • 8
  • 48
  • 83
Muhammad Ahmed AbuTalib
  • 4,080
  • 4
  • 36
  • 59

2 Answers2

2

Try this:

SELECT vs.version
FROM version_sorting vs
ORDER BY CAST(SUBSTRING(vs.version,2) AS SIGNED), vs.version;
Saharsh Shah
  • 28,687
  • 8
  • 48
  • 83
1

could you try this?

SELECT version
FROM version_sorting
ORDER BY LENGTH(version),  version;
Jason Heo
  • 9,956
  • 2
  • 36
  • 64