I have numbers saved as VARCHAR to a MySQL database. I can not make them INT due to some other depending circumstances.

It is taking them as character not as number while sorting.

In database I have

1 2 3 4 5 6 7 8 9 10...

On my page it shows ordered list like this:

1 10 2 3 4 5 6 7 8 9

How can I make it appear ordered by numbers ascending?

推荐答案

If possible you should change the data type of the column to a number if you only store numbers anyway.

If you can't do that then cast your column value to an integer explicitly with

select col from yourtable
order by cast(col as unsigned)

or implicitly for instance with a mathematical operation which forces a conversion to number

select col from yourtable
order by col + 0

BTW MySQL converts strings from left to right. Examples:

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 */

Mysql相关问答推荐

配置MySQL服务器以管理数千个表

客户跨订阅的跨时间线计数

了解MySQL_stmt_BIND_NAMED_Param()-MySQL C API

用于将具有多个状态更改日期列的单行转换为具有状态和时间戳的多行的SQL查询

如何合并有多行的json列

docker-compose:无法将应用程序服务连接到 mysql 数据库,收到错误:用户‘root’@‘localhost’访问被拒绝(使用密码:YES)

MySQL,递归 CTE.它如何以这种句法形式工作?

为什么order by子句可以利用索引?

MySQL DISTINCT 日期仅返回特定表的 1 个值.相同的查询适用于其他表

MySql部分匹配基于部分查询代码

多个驱动器上的 MYSQL 数据

MySQL 8 - MBRContains 不使用空间索引

MySQL IF() 函数根据指定条件执行代码块

从 2 个不同的表中获取数据并将它们加入 sql

限制正则​​表达式中多字符通配符的范围

SQL 中的双杠 (||) 是什么意思?

如何在 MySQL 中 Select 字段具有最小值的数据?

如何在mysql中连接整数(整数和整数)和varchar(nvarchar和varchar)等数据类型?

我如何决定何时使用右连接/左连接或内连接或者如何确定哪个表在哪一侧?

如何在 MySQL 中删除此索引?