登录
首页 >  数据库 >  MySQL

按两列对 MySQL 表进行排序?

来源:tutorialspoint

时间:2023-08-30 09:34:33 404浏览 收藏

知识点掌握了,还需要不断练习才能熟练运用。下面golang学习网给大家带来一个数据库开发实战,手把手教大家学习《按两列对 MySQL 表进行排序?》,在实现功能的过程中也带大家重新温习相关知识点,温故而知新,回头看看说不定又有不一样的感悟!

借助以下语法按两列对 MySQL 表进行排序 -

order by yourColumnName1 DESC,yourColumnName2 DESC;

让我们首先为我们的示例创建一个表 -

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

借助insert命令向表中插入记录。查询如下 -

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)

现在,应用上述语法对 MySQL 表中的两列进行排序。查询如下 -

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

以下是按升序对两列进行排序的输出 -

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

或者您可以借助 DESC 命令按降序执行。查询如下 -

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

以下是输出 -

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

注意 - 主要排序首先起作用。

以上就是《按两列对 MySQL 表进行排序?》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:tutorialspoint 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>