If we use the ORDER BY clause when calculating dates, it will be more convenient to find records. To understand it, we get the data from the table "Collegedetail" as follows -
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)
Now, suppose we want to calculate the historical years of a college, then it can be done as follows -
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)
If we use the following ORDER BY clause when calculating the number of years the university was founded, our search will be more convenient -
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)
The above result set shows that we can very well achieve this by using the ORER BY clause with "YEARS_OLD" Search the oldest universities easily. We can also use DESC keyword with ORDER BY clause which returns the oldest university in the top row as shown below -
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)
The above is the detailed content of How to use ORDER BY clause when calculating dates?. For more information, please follow other related articles on the PHP Chinese website!