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.【mysql|mysql 基础使用(三)】MySQL 提供了好几种日期计算函数。
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.
确定每个pets的年龄,我们可以用TIMESTAMPDIFF()函数,age是用来装饰用的,让结果看的更容易懂。
文章图片
文章图片
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:
文章图片
To sort the output by age rather than name, just use a different ORDER BY clause:
文章图片
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 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(),用来获取年月日
文章图片
这里获取的月份要注意12月,不能加一了
文章图片
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 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;
推荐阅读
- 由浅入深理解AOP
- 【译】20个更有效地使用谷歌搜索的技巧
- mybatisplus如何在xml的连表查询中使用queryWrapper
- MybatisPlus|MybatisPlus LambdaQueryWrapper使用int默认值的坑及解决
- MybatisPlus使用queryWrapper如何实现复杂查询
- iOS中的Block
- Linux下面如何查看tomcat已经使用多少线程
- 使用composer自动加载类文件
- android|android studio中ndk的使用
- Python基础|Python基础 - 练习1