MySQL 的 order by 选项按字符串(而非数字)进行排序?


如果表中字段是 varchar 数据类型,可以按如下语法进行排序 −

select yourColumnName FROM yourTableName ORDER BY yourColumnName +0 DESC;

为了理解上述语法,我们创建一个表。创建表的查询如下 −

mysql> create table selectOrderdemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Name varchar(100),
   -> RankNumber varchar(100)
   -> );
Query OK, 0 rows affected (0.55 sec)

使用 insert 命令在表中插入一些记录。查询如下 −

mysql> insert into selectOrderdemo(Name,RankNumber) values('Larry',-100);
Query OK, 1 row affected (0.23 sec)
mysql> insert into selectOrderdemo(Name,RankNumber) values('John',50);
Query OK, 1 row affected (0.13 sec)
mysql> insert into selectOrderdemo(Name,RankNumber) values('Bob',0);
Query OK, 1 row affected (0.14 sec)
mysql> insert into selectOrderdemo(Name,RankNumber) values('Carol',-110);
Query OK, 1 row affected (0.23 sec)
mysql> insert into selectOrderdemo(Name,RankNumber) values('David',98);
Query OK, 1 row affected (0.21 sec

使用 select 语句从表中显示所有记录。查询如下 −

mysql> select *from selectOrderdemo;

以下是输出 −

+----+-------+------------+
| Id | Name  | RankNumber |
+----+-------+------------+
| 1  | Larry | -100       |
| 2  | John  | 50         |
| 3  | Bob   | 0          |
| 4  | Carol | -110       |
| 5  | David | 98         |
+----+-------+------------+
5 rows in set (0.00 sec)

以下是按数字顺序选择 order by 的查询。

情况 1 − 如果要按降序排列,查询如下 −

mysql> select RankNumber FROM selectOrderdemo ORDER BY RankNumber+0 DESC;

以下是输出 −

+------------+
| RankNumber |
+------------+
| 98         |
| 50         |
| 0          |
| -100       |
| -110       |
+------------+
5 rows in set (0.00 sec)

情况 2 − 如果要按升序排列,查询如下 −

mysql> select RankNumber FROM selectOrderdemo ORDER BY RankNumber+0;

以下是输出 −

+------------+
| RankNumber |
+------------+
| -110       |
| -100       |
| 0          |
| 50         |
| 98         |
+------------+
5 rows in set (0.00 sec)

情况 3 − 如果要显示所有列,请使用以下查询 −

mysql> select * FROM selectOrderdemo ORDER BY RankNumber+0 DESC;

以下是输出 −

+----+-------+------------+
| Id | Name  | RankNumber |
+----+-------+------------+
| 5  | David | 98         |
| 2  | John  | 50         |
| 3  | Bob   | 0          |
| 1  | Larry | -100       |
| 4  | Carol | -110       |
+----+-------+------------+
5 rows in set (0.00 sec)

更新日期:2019-07-30

166 次浏览

开启您的事业

完成课程并获得认证

开始
广告