我们如何使用函数在MySQL中计算日期?
在MySQL中,我们可以使用以下函数来计算Date-
CURDATE()函数-基本上,它返回计算机的当前日期。
YEAR()函数-返回指定日期的年份。
MONTH()函数-它返回指定日期的月份。
DAY()函数-它返回指定日期的日期。
RIGHT()函数-从给定日期返回函数中指定的字符数。比较RIGHT()
函数返回值的表达式部分的值为1或0。
要理解它,请请看以下来自名为“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)
在以下查询中,我们通过使用所有不同的日期函数来计算DATE-
mysql> Select ID, Estb, CURDATE(), YEAR(Estb), MONTH(Estb), DAY(Estb), (RIGHT(CURDATE(),5) < RIGHT(estb,5))As 'Return' FROM Collegedetail; +------+------------+------------+------------+-------------+-----------+--------+ | ID | Estb | CURDATE() | YEAR(Estb) | MONTH(Estb) | DAY(Estb) | Return | +------+------------+------------+------------+-------------+-----------+--------+ | 111 | 2010-05-01 | 2017-11-30 | 2010 | 5 | 1 | 0 | | 130 | 1995-10-25 | 2017-11-30 | 1995 | 10 | 25 | 0 | | 139 | 1994-09-25 | 2017-11-30 | 1994 | 9 | 25 | 0 | | 1539 | 2001-07-23 | 2017-11-30 | 2001 | 7 | 23 | 0 | | 1545 | 2010-07-30 | 2017-11-30 | 2010 | 7 | 30 | 0 | +------+------------+------------+------------+-------------+-----------+--------+ 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)