在计算日期时如何使用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)
上面的结果集表明,通过使用带有'YEARS_OLD'的ORER BY子句,我们可以很容易地搜索最早的大学。我们还可以将DESC关键字与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 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)
以上是 在计算日期时如何使用ORDER BY子句? 的全部内容, 来源链接: utcz.com/z/334919.html