How to Order MySQL VARCHAR Results
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-bhMySQL would return the select something like the following:
987
12-a 1234 13-bhIt puts three character long results before four character long results and so on. I would like it to ignore length and just sort the numbers that come before the '-' char. Is there something that I can ORDER on like SUBSTRING in an IF() which would remove all data in a row starting with the '-' char, so that I can CAST as an integer?
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;
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.
...
....
CAST(COL as SIGNED) DESC
精彩评论