如何在 MySQL 中一次对多列进行排序?


若要一次对多列排序,可以使用 ORDER BY 子句。以下是语法 −

select yourColumnName1,yourColumnName2,yourColumnName3 from yourTableName
order by yourColumnName2,yourColumnName3;

我们先创建一个表 −

mysql> create table doubleSortDemo
   -> (
   -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> StudentName varchar(100),
   -> StudentCountryName varchar(10)
   -> );
Query OK, 0 rows affected (0.71 sec)

下面是使用 insert 命令在表中插入记录的查询 −

mysql> insert into doubleSortDemo(StudentName,StudentCountryName)
values('John','AUS');
Query OK, 1 row affected (0.21 sec)
mysql> insert into doubleSortDemo(StudentName,StudentCountryName) values('Sam','UK');
Query OK, 1 row affected (0.20 sec)
mysql> insert into doubleSortDemo(StudentName,StudentCountryName) values('Bob','US');
Query OK, 1 row affected (0.16 sec)
mysql> insert into doubleSortDemo(StudentName,StudentCountryName) values('Carol','UK');
Query OK, 1 row affected (0.32 sec)
mysql> insert into doubleSortDemo(StudentName,StudentCountryName)
values('David','AUS');
Query OK, 1 row affected (0.19 sec)
mysql> insert into doubleSortDemo(StudentName,StudentCountryName) values('Larry','UK');
Query OK, 1 row affected (0.15 sec)

下面是使用 select 语句从表中显示所有记录的查询 −

mysql> select * from doubleSortDemo;

这将产生以下输出 −

+-----------+-------------+--------------------+
| StudentId | StudentName | StudentCountryName |
+-----------+-------------+--------------------+
| 1         | John        | AUS                |
| 2         | Sam         | UK                 |
| 3         | Bob         | US                 |
| 4         | Carol       | UK                 |
| 5         | David       | AUS                |
| 6         | Larry       | UK                 |
+-----------+-------------+--------------------+
6 rows in set (0.00 sec)

以下是执行 MySQL 排序的查询,涉及到多列,即学生国家和姓名 −

mysql> select StudentId,StudentName,StudentCountryName from doubleSortDemo
   -> order by StudentCountryName,StudentName;

这将产生以下输出 −

+-----------+-------------+--------------------+
| StudentId | StudentName | StudentCountryName |
+-----------+-------------+--------------------+
| 5         | David       | AUS                |
| 1         | John        | AUS                |
| 4         | Carol       | UK                 |
| 6         | Larry       | UK                 |
| 2         | Sam         | UK                 |
| 3         | Bob         | US                 |
+-----------+-------------+--------------------+
6 rows in set (0.00 sec)

更新于: 2019 年 7 月 30 日

102 次浏览

开启您的 职业生涯

完成课程以取得认证

开始
广告