MySQL查询在数字列中显示ASC顺序?
您可以借助CAST()
方法来实现。让我们首先创建一个表-
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, Score int ); Query OK, 0 rows affected (0.72 sec)
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable(Score) values(10); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable(Score) values(100); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable(Score) values(11); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable(Score) values(97); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable(Score) values(78); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable(Score) values(89); Query OK, 1 row affected (0.18 sec)
使用select语句显示表中的所有记录-
mysql> select *from DemoTable;
这将产生以下输出-
+----+-------+ | Id | Score | +----+-------+ | 1 | 10 | | 2 | 100 | | 3 | 11 | | 4 | 97 | | 5 | 78 | | 6 | 89 | +----+-------+ 6 rows in set (0.00 sec)
以下是在数字列中设置ASC顺序的查询-
mysql> select *from DemoTable order by cast(Score AS SIGNED INTEGER) ASC;
这将产生以下输出-
+----+-------+ | Id | Score | +----+-------+ | 1 | 10 | | 3 | 11 | | 5 | 78 | | 6 | 89 | | 4 | 97 | | 2 | 100 | +----+-------+ 6 rows in set (0.00 sec)