How to Order MySQL VARCHAR Results

帅比萌擦擦* 提交于 2019-12-19 07:22:33

问题


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 return the select something like the following:

987
12-a
1234
13-bh

It 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?


回答1:


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;



回答2:


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.




回答3:


...
....
CAST(COL as SIGNED)  DESC


来源:https://stackoverflow.com/questions/5055049/how-to-order-mysql-varchar-results

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!