按两个列对 MySQL 表进行排序?


借助下面语法按两个列对 MySQL 表进行排序 −

order by yourColumnName1 DESC,yourColumnName2 DESC;

让我们先创建一个表用于示例 −

mysql> create table OrderByDemo
   -> (
   -> StudentId int,
   -> StudentName varchar(100),
   -> StudentAge int
   -> );
Query OK, 0 rows affected (0.57 sec)

使用插入命令向表中插入记录。查询如下所示 −

mysql> insert into OrderByDemo values(1,'John',23);
Query OK, 1 row affected (0.20 sec)
mysql> insert into OrderByDemo values(3,'Johnson',24);
Query OK, 1 row affected (0.27 sec)
mysql> insert into OrderByDemo values(4,'Carol',26);
Query OK, 1 row affected (0.14 sec)
mysql> insert into OrderByDemo values(2,'David',20);
Query OK, 1 row affected (0.13 sec)

现在,应用以上语法对 MySQL 表中的两个列进行排序。查询如下所示 −

mysql> select *from OrderByDemo order by StudentId ASC, StudentAge ASC;

以下输出按升序对两列进行排序 −

+-----------+-------------+------------+
| StudentId | StudentName | StudentAge |
+-----------+-------------+------------+
|         1 | John        |         23 |
|         2 | David       |         20 |
|         3 | Johnson     |         24 |
|         4 | Carol       |         26 |
+-----------+-------------+------------+
4 rows in set (0.00 sec)

或者可以使用 DESC 命令按降序排序。查询如下所示 −

mysql> select *from OrderByDemo order by StudentId DESC,StudentAge DESC;

以下为输出 −

+-----------+-------------+------------+
| StudentId | StudentName | StudentAge |
+-----------+-------------+------------+
|         4 | Carol       |         26 |
|         3 | Johnson     |         24 |
|         2 | David       |         20 |
|         1 | John        |         23 |
+-----------+-------------+------------+
4 rows in set (0.00 sec)

− 首先进行主排序。

更新于:30-Jul-2019

494 次浏览

开启你的职业生涯

完成课程,获得认证

开始学习
广告