MySQL 如何同时排序多列

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)

以下是使用插入命令插入表中记录的查询 –

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)

阅读更多:MySQL 教程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程