我们可以创建一个函数,该函数接受日期值作为其参数并返回年,月和日的差值,如下所示
mysql> CREATE FUNCTION date_difference(Date1 DATE, date2 DATE) RETURNS VARCHAR(30) -> RETURN CONCAT( -> @years := TIMESTAMPDIFF(YEAR, date1, date2),IF (@years = 1, ' year, ', ' years, '), -> @months := TIMESTAMPDIFF(MONTH, DATE_ADD(date1, INTERVAL @years YEAR), date2),IF (@months = 1, ' month, ', ' months, '), -> @days := TIMESTAMPDIFF(DAY, DATE_ADD(date1, INTERVAL @years * 12 + @months MONTH), date2),IF (@days = 1, ' day', ' days')) ;
现在,将date的值作为参数传递给函数date_difference
mysql> Select date_difference('2015-11-16','2016-12-17') AS Difference; +------------------------+ | Difference | +------------------------+ | 1 year, 1 month, 1 day | +------------------------+ 1 row in set (0.00 sec)
上面的结果集给出了两个指定日期之间的差值作为函数的参数。