- 3.3.4.5 Date Calculations
MySQL provides several functions that you can use to perform calculations on dates, for example, to calculate ages or extract parts of dates.
To determine how many years old each of your pets is, use theTIMESTAMPDIFF()
function. Its arguments are the unit in which you want the result expressed, and the two date for which to take the difference. The following query shows, for each pet, the birth date, the current date, and the age in years. An alias (age
) is used to make the final output column label more meaningful.
MySQL 提供了好几种日期计算函数。
确定每个pets的年龄,我们可以用TIMESTAMPDIFF()函数,age是用来装饰用的,让结果看的更容易懂。
What if you want to know which animals have birthdays next month? For this type of calculation, year and day are irrelevant; you simply want to extract the month part of the
birth
column. MySQL provides several functions for extracting parts of dates, such asYEAR()
,MONTH()
, andDAYOFMONTH()
.MONTH()
is the appropriate function here. To see how it works, run a simple query that displays the value of bothbirth
andMONTH(birth)
如果你想知道哪些动物下个月有生日,该怎么办?
这种计算和year和day是没有联系的,你只是想取货month,MySQL提供了YEAR(), MONTH(), and DAYOFMONTH(),用来获取年月日
You can write the query so that it works no matter what the current month is, so that you do not have to use the number for a particular month.
DATE_ADD()
enables you to add a time interval to a given date. If you add a month to the value ofCURDATE()
, then extract the month part withMONTH()
, the result produces the month in which to look for birthdays:
mysql> SELECT name, birth FROM pet
-> WHERE MONTH(birth) = MONTH(DATE_ADD(CURDATE(),INTERVAL 1 MONTH));
mysql> SELECT name, birth FROM pet
-> WHERE MONTH(birth) = MOD(MONTH(CURDATE()), 12) + 1;