How to Order MySQL VARCHAR Results

后端 未结 3 402
傲寒
傲寒 2021-01-13 00:54

In a SELECT statement, I have a varchar column with ORDER BY DESC on it. Examples of data in this column:

1234
987
12-a
13-bh

MySQL would r

相关标签:
3条回答
  • 2021-01-13 01:12

    The trick part is dealing about the "-": since its optional, you cant directly use SUBSTR in that field (as Marc B pointed out) to get rid of everything after it

    So, the trick would be: append an "-" to the value!

    Like this:

    ORDER BY CAST(SUBSTR(CONCAT(yourfield,'-'), 0, LOCATE('-', CONCAT(yourfield,'-'))) AS UNSIGNED)
    

    Another useful approach is to, instead of using SUBSTR to "remove" everything after the "-", replace it (and all letters) to "0", and THEN use CAST.

    0 讨论(0)
  • 2021-01-13 01:14

    The easiest thing to do is this

    SELECT *
    FROM TBL
    ORDER BY VARCHAR_COLUMN * 1;
    

    To see what is happening, just add the column I used for ordering

    SELECT *, VARCHAR_COLUMN * 1
    FROM TBL
    ORDER BY VARCHAR_COLUMN * 1;
    
    0 讨论(0)
  • 2021-01-13 01:27
    ...
    ....
    CAST(COL as SIGNED)  DESC
    
    0 讨论(0)
提交回复
热议问题