我将数字以VARCHAR
的形式保存到MySQL数据库中.由于其他一些情况,我不能把它们改成INT
.
它是在排序时将它们作为字符而不是数字.
在我的数据库里
1 2 3 4 5 6 7 8 9 10...
在我的页面上,它显示如下有序列表:
1 10 2 3 4 5 6 7 8 9
我如何让它看起来按数字升序排列?
我将数字以VARCHAR
的形式保存到MySQL数据库中.由于其他一些情况,我不能把它们改成INT
.
它是在排序时将它们作为字符而不是数字.
在我的数据库里
1 2 3 4 5 6 7 8 9 10...
在我的页面上,它显示如下有序列表:
1 10 2 3 4 5 6 7 8 9
我如何让它看起来按数字升序排列?
如果可能,如果只存储数字,则应将列的数据类型更改为数字.
如果你做不到这一点,那么用
select col from yourtable
order by cast(col as unsigned)
或者implicitly,比如一个数学运算,强制转换成数字
select col from yourtable
order by col + 0
顺便说一句,MySQL从左到右转换字符串.例如:
string value | integer value after conversion
--------------+--------------------------------
'1' | 1
'ABC' | 0 /* the string does not contain a number, so the result is 0 */
'123miles' | 123
'$123' | 0 /* the left side of the string does not start with a number */