在数据库中将字符串按数字排序?


如果要按数字对字符串进行排序,请使用 CAST()。以下为该语法:-

select *from yourTableName ORDER BY CAST(yourColumnName AS SIGNED) DESC;

我们来先创建一个表:-

mysql> create table DemoTable
   (
   Id varchar(100)
   );
Query OK, 0 rows affected (0.18 sec)

在表中插入一些记录,使用 insert 命令:-

mysql> insert into DemoTable values('3');
Query OK, 1 row affected (0.07 sec)

mysql> insert into DemoTable values('20');
Query OK, 1 row affected (0.07 sec)

mysql> insert into DemoTable values('34');
Query OK, 1 row affected (0.06 sec)

mysql> insert into DemoTable values('21');
Query OK, 1 row affected (0.06 sec)

mysql> insert into DemoTable values('78');
Query OK, 1 row affected (0.04 sec)

mysql> insert into DemoTable values('90');
Query OK, 1 row affected (0.07 sec)

使用 select 语句显示表中的所有记录:-

mysql> select *from DemoTable;

将生成以下输出:-

+------+
| Id   |
+------+
| 3    |
| 20   |
| 34   |
| 21   |
| 78   |
| 90   |
+------+
6 rows in set (0.00 sec)

以下是对整数进行排序的查询:-

mysql> select *from DemoTable ORDER BY CAST(Id AS SIGNED) DESC;

将生成以下输出:-

+------+
| Id   |
+------+
| 90   |
| 78   |
| 34   |
| 21   |
| 20   |
| 3    |
+------+
6 rows in set (0.02 sec)

更新于: 30-Jul-2019

82 次浏览

职业生涯开始

完成课程并获得认证

立即开始
广告