mysql|mysql 基础使用(三)

  • 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 the TIMESTAMPDIFF()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|mysql 基础使用(三)】MySQL 提供了好几种日期计算函数。
确定每个pets的年龄,我们可以用TIMESTAMPDIFF()函数,age是用来装饰用的,让结果看的更容易懂。
mysql|mysql 基础使用(三)
文章图片
mysql|mysql 基础使用(三)
文章图片
The query works, but the result could be scanned more easily if the rows were presented in some order. This can be done by adding an ORDER BY name clause to sort the output by name: mysql|mysql 基础使用(三)
文章图片
To sort the output by age rather than name, just use a different ORDER BY clause:
mysql|mysql 基础使用(三)
文章图片
A similar query can be used to determine age at death for animals that have died. You determine which animals these are by checking whether the death value is NULL. Then, for those with non-NULL values, compute the difference between the death and birth values; The query uses death IS NOT NULL rather than death <> NULL because NULL is a special value that cannot be compared using the usual comparison operators.
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 as YEAR(), MONTH(), and DAYOFMONTH().MONTH() is the appropriate function here. To see how it works, run a simple query that displays the value of both birth and MONTH(birth)
如果你想知道哪些动物下个月有生日,该怎么办?
这种计算和year和day是没有联系的,你只是想取货month,MySQL提供了YEAR(), MONTH(), and DAYOFMONTH(),用来获取年月日

mysql|mysql 基础使用(三)
文章图片
这里获取的月份要注意12月,不能加一了 mysql|mysql 基础使用(三)
文章图片
Finding animals with birthdays in the upcoming month is also simple. Suppose that the current month is April. Then the month value is 4 and you can look for animals born in May (month 5) like this:
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 of CURDATE(), then extract the month part with MONTH(), 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;

    推荐阅读