Home > Database > Mysql Tutorial > body text

Sort MySQL table by two columns?

WBOY
Release: 2023-09-04 19:53:10
forward
1337 people have browsed it

按两列对 MySQL 表进行排序?

Sort a MySQL table by two columns with the help of the following syntax -

order by yourColumnName1 DESC,yourColumnName2 DESC;
Copy after login

Let us first create a table for our example -

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

With the help of The insert command inserts records into the table. The query is as follows -

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)
Copy after login

Now, apply the above syntax to sort the two columns in the MySQL table. The query is as follows -

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

The following is the output of sorting the two columns in ascending order -

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

Or you can do it in descending order with the help of DESC command. The query is as follows -

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

The following is the output -

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

Note - Primary sorting works first.

The above is the detailed content of Sort MySQL table by two columns?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template