要一次对一个以上的列进行排序,可以使用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) -> );
以下是使用insert命令在表中插入记录的查询-
mysql> insert into doubleSortDemo(StudentName,StudentCountryName) values('John','AUS'); mysql> insert into doubleSortDemo(StudentName,StudentCountryName) values('Sam','UK'); mysql> insert into doubleSortDemo(StudentName,StudentCountryName) values('Bob','US'); mysql> insert into doubleSortDemo(StudentName,StudentCountryName) values('Carol','UK'); mysql> insert into doubleSortDemo(StudentName,StudentCountryName) values('David','AUS'); mysql> insert into doubleSortDemo(StudentName,StudentCountryName) values('Larry','UK');
以下是使用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)