如果我們在計算日期時使用 ORDER BY 子句,查找記錄會更方便。為了理解它,我們從表“Collegedetail”中獲取數(shù)據(jù),如下 –
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)
登錄后復制
現(xiàn)在,假設(shè)我們想計算一所大學的歷史年數(shù),那么可以按如下方式完成 –
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)
登錄后復制
如果我們在計算大學成立年數(shù)時使用如下 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)
登錄后復制
上面的結(jié)果集顯示,我們可以通過使用帶有“YEARS_OLD”的 ORER BY 子句非常輕松地搜索最古老的大學。我們還可以將 DESC 關(guān)鍵字與 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_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)
登錄后復制
以上就是在計算日期時如何使用 ORDER BY 子句?的詳細內(nèi)容,更多請關(guān)注www.92cms.cn其它相關(guān)文章!