利用函数,我们如何返回两个日期值之间的年、月和天的差?
我们可以创建如下所示的函数,它将日期值作为其参数,并返回年、月和天的差
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')) ; Query OK, 0 rows affected (0.00 sec)
现在,将日期的值作为参数传递到函数 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)
以上结果集给出两个指定日期之间的差作为函数的参数。
广告