如何在 MySQL 中一次对多个列进行排序?
mysqlmysqli database更新于 2025/1/22 7:08:17
要一次对多个列进行排序,可以使用 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)
相关文章
有用资源
mysql 参考教程 - 该教程包含有关 mysql 的更多信息:https://www.cainiaomax.com/mysql/

