在计算日期时如何使用 ORDER BY 子句?


如果在计算日期时使用 ORDER BY 子句,查找记录将会更容易。要理解这一点,我们获取表“Collegedetail”中的数据,如下所示:

mysql> Select * from Collegedetail;
+------+---------+------------+
| ID   | Country | Estb       |
+------+---------+------------+
| 111  | INDIA   | 2010-05-01 |
| 130  | INDIA   | 1995-10-25 |
| 139  | USA     | 1994-09-25 |
| 1539 | UK      | 2001-07-23 |
| 1545 | Russia  | 2010-07-30 |
+------+---------+------------+
5 rows in set (0.00 sec)

现在,假设如果我们想要计算一所大学的年数,则可以按如下方式进行计算:

mysql> Select ID, estb, CURDATE(),((YEAR(CURDATE())-YEAR(estb))-(RIGHT(CURDATE(),5)<RIGHT(estb,5))) AS 'YEARS_OLD' from collegedetail;
+------+------------+------------+-----------+
| ID   | estb       | CURDATE()  | YEARS_OLD |
+------+------------+------------+-----------+
| 111  | 2010-05-01 | 2017-11-30 |         7 |
| 130  | 1995-10-25 | 2017-11-30 |        22 |
| 139  | 1994-09-25 | 2017-11-30 |        23 |
| 1539 | 2001-07-23 | 2017-11-30 |        16 |
| 1545 | 2010-07-30 | 2017-11-30 |         7 |
+------+------------+------------+-----------+
5 rows in set (0.00 sec)

如果我们在计算一所学校的年数时使用 ORDER BY 子句,则我们的搜索会更方便,如下所示:

mysql> Select ID, estb, CURDATE(),((YEAR(CURDATE())-YEAR(estb))-(RIGHT(CURDATE(),5)<RIGHT(estb,5))) AS 'YEARS_OLD' from collegedetail ORDER BY YEARS_OLD;
+------+------------+------------+-----------+
| ID   | estb       | CURDATE()  | YEARS_OLD |
+------+------------+------------+-----------+
| 111  | 2010-05-01 | 2017-11-30 |         7 |
| 1545 | 2010-07-30 | 2017-11-30 |         7 |
| 1539 | 2001-07-23 | 2017-11-30 |        16 |
| 130  | 1995-10-25 | 2017-11-30 |        22 |
| 139  | 1994-09-25 | 2017-11-30 |        23 |
+------+------------+------------+-----------+
5 rows in set (0.01 sec)

以上结果集表明,我们可以通过将 ORER BY 子句与“YEARS_OLD”一起使用,非常轻松地搜索最古老的大学。我们还可以在 ORDER BY 子句中使用 DESC 关键字,如下所示,该关键字将在顶部行返回最古老的大学:

mysql> Select ID, estb, CURDATE(),((YEAR(CURDATE())-YEAR(estb))-(RIGHT(CURDATE(),5)<RIGHT(estb,5))) AS 'YEARS_OLD' from collegedetail ORDER BY YEARS_O
LD DESC;
+------+------------+------------+-----------+
| ID   | estb       | CURDATE()  | YEARS_OLD |
+------+------------+------------+-----------+
| 139  | 1994-09-25 | 2017-11-30 |        23 |
| 130  | 1995-10-25 | 2017-11-30 |        22 |
| 1539 | 2001-07-23 | 2017-11-30 |        16 |
| 111  | 2010-05-01 | 2017-11-30 |         7 |
| 1545 | 2010-07-30 | 2017-11-30 |         7 |
+------+------------+------------+-----------+
5 rows in set (0.00 sec)

更新于: 2020 年 6 月 20 日

106 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告