MySQL中有很多的有用的函数,特别是日期,在处理业务的时候在数据库中就可以处理,今天就整理一下日期的相关函数
一、MySQL中的常用函数
-
NOW()
- 获取当前数据库的日期和时间,如:2018-09-28 10:09:12
-
CURDATE()
- 获取当前数据库的日期,如:2018-09-28
-
CURTIME()
- 获取当前数据库的时间,如:10:12:32
-
DATE(
) - 获取指定日期时间对象的日期部分
-
EXTRACT(
FROM ) - 获取
部分的所有日期时间模块, 部分如下表所示: Unit 值 含义 MICROSECOND 微秒 SECOND 秒-ss MINUTE 分钟-mm HOUR 小时-HH/hh DAY 日期的天-dd WEEK 周几 MONTH 第几月 QUARTER 第几季度 YEAR 哪年 SECOND_MICROSECOND MINUTE_MICROSECOND MINUTE_SECOND HOUR_MICROSECOND HOUR_SECOND HOUR_MINUTE DAY_MICROSECOND DAY_SECOND DAY_MINUTE DAY_HOUR YEAR_MONTH 输出指定日期结果:
- 获取
DATE_ADD()
DATE_SUB()
DATEDIFF()
DATE_FORMAT()
-
其他的一些函数
函数名 描述 ADDDATE()
Add time values (intervals) to a date value ADDTIME()
Add time CONVERT_TZ()
Convert from one time zone to another CURDATE()
Return the current date CURRENT_DATE()
,CURRENT_DATE
Synonyms for CURDATE() CURRENT_TIME()
,CURRENT_TIME
Synonyms for CURTIME() CURRENT_TIMESTAMP()
,CURRENT_TIMESTAMP
Synonyms for NOW() CURTIME()
Return the current time DATE()
Extract the date part of a date or datetime expression DATE_ADD()
Add time values (intervals) to a date value DATE_FORMAT()
Format date as specified DATE_SUB()
Subtract a time value (interval) from a date DATEDIFF()
Subtract two dates DAY()
Synonym for DAYOFMONTH() DAYNAME()
Return the name of the weekday DAYOFMONTH()
Return the day of the month (0-31) DAYOFWEEK()
Return the weekday index of the argument DAYOFYEAR()
Return the day of the year (1-366) EXTRACT()
Extract part of a date FROM_DAYS()
Convert a day number to a date FROM_UNIXTIME()
Format Unix timestamp as a date GET_FORMAT()
Return a date format string HOUR()
Extract the hour LAST_DAY
Return the last day of the month for the argument LOCALTIME()
,LOCALTIME
Synonym for NOW() LOCALTIMESTAMP
,LOCALTIMESTAMP()
Synonym for NOW() MAKEDATE()
Create a date from the year and day of year MAKETIME()
Create time from hour, minute, second MICROSECOND()
Return the microseconds from argument MINUTE()
Return the minute from the argument MONTH()
Return the month from the date passed MONTHNAME()
Return the name of the month NOW()
Return the current date and time PERIOD_ADD()
Add a period to a year-month PERIOD_DIFF()
Return the number of months between periods QUARTER()
Return the quarter from a date argument SEC_TO_TIME()
Converts seconds to 'HH:MM:SS' format SECOND()
Return the second (0-59) STR_TO_DATE()
Convert a string to a date SUBDATE()
Synonym for DATE_SUB() when invoked with three arguments SUBTIME()
Subtract times SYSDATE()
Return the time at which the function executes TIME()
Extract the time portion of the expression passed TIME_FORMAT()
Format as time TIME_TO_SEC()
Return the argument converted to seconds TIMEDIFF()
Subtract time TIMESTAMP()
With a single argument, this function returns the date or datetime expression; with two arguments, the sum of the arguments TIMESTAMPADD()
Add an interval to a datetime expression TIMESTAMPDIFF()
Subtract an interval from a datetime expression TO_DAYS()
Return the date argument converted to days TO_SECONDS()
Return the date or datetime argument converted to seconds since Year 0 UNIX_TIMESTAMP()
Return a Unix timestamp UTC_DATE()
Return the current UTC date UTC_TIME()
Return the current UTC time UTC_TIMESTAMP()
Return the current UTC date and time WEEK()
Return the week number WEEKDAY()
Return the weekday index WEEKOFYEAR()
Return the calendar week of the date (1-53) YEAR()
Return the year YEARWEEK()
Return the year and week
二、MySQL本周、本月、上一月的写法
-
今天
= to_days(NOW()) -
昨天
TO_DAYS(NOW()) - TO_DAYS(
) < = 1 -
近7天
DATE_SUB(CURDATE(), INTERVAL 7 DAY) < = date(
) -
近30天
SELECT * FROM 表名 WHERE DATE_SUB(CURDATE(), INTERVAL 30 DAY) < = date(
) -
本周
YEARWEEK(DATE_FORMAT(
,'%Y-%m-%d')) = YEARWEEK(NOW()); -
上周
YEARWEEK(DATE_FORMAT(
,'%Y-%m-%d')) = YEARWEEK(NOW())-1; -
本月
DATE_FORMAT(
, '%Y%m') = DATE_FORMAT(CURDATE(), '%Y%m') -
上月
PERIOD_DIFF(DATE_FORMAT(NOW(), '%Y%m'), DATE_FORMAT(
, '%Y%m' )) = 1 -
本季度
QUARTER(create_date) = QUARTER(NOW())
-
上季度
QUARTER(create_date) = QUARTER(DATE_SUB(NOW(),INTERVAL 1 QUARTER))
-
本年
YEAR(create_date) = YEAR(NOW())
-
去年
YEAR(create_date) = YEAR(DATE_SUB(NOW(), INTERVAL 1 YEAR))
-
查询当前月份的数据
DATE_FORMAT(
,'%Y-%m') = DATE_FORMAT(NOW(), '%Y-%m') -
查询距离当前现在6个月的数据
BETWEEN DATE_SUB(NOW(), INTERVAL 6 MONTH) AND NOW()
三、MySQL 使用下列数据类型在数据库中存储日期或日期/时间值:
- DATE - 格式 YYYY-MM-DD
- DATETIME - 格式: YYYY-MM-DD HH:MM:SS
- TIMESTAMP - 格式: YYYY-MM-DD HH:MM:SS
- YEAR - 格式 YYYY 或 YY
四、INT、TIMESTAMP和DATETIME存储时间
- 三者存储时间的区别
-
INT
- 占用4个字节(INT的长度是4个字节);存储空间上比DATETIME少,int索引存储空间也相对较小,排序和查询效率相对较高一点点;
- 可读性极差,无法直观的看到数据;
-
TIMESTAMP
- 占用4个字节;
- 以UTC国际标准时间格式保存;
- 自动时区转化:存储时对当前的时区进行转换,检索时再转换回当前的时区;
- TIMESTAMP取值范围:1970-01-01 00:00:00 到 2038-01-19 03:14:07;
-
DATETIME
- 占用8个字节;
- 相对于TIMESTAMP,DATETIME不考虑时区,进去什么样,出来就什么样;
- DATETIME取值范围:00:00:00'到'9999-12-31 23:59:59';
-
- TIMESTAMP的自动更新特性
在我们创建表的时候如果一个字段是timestamp,系统会默认给这个字段添加:
DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
;这个特性是自动初始化和自动更新(Automatic Initialization and Updating)。自动初始化指的是如果对该字段没有显性赋值,则自动设置为当前系统时间,即
DEFAULT CURRENT_TIMESTAMP
。自动更新指的是如果修改了其它字段,则该字段的值将自动更新为当前系统时间,即:ON UPDATE CURRENT_TIMESTAMP
。它与explicit_defaults_for_timestamp
参数有关。-
官方的原文如下:
As of MySQL 5.6.5,
TIMESTAMP
andDATETIME
columns can be automatically initializated and updated to the current date and time (that is, the current timestamp). Before 5.6.5, this is true only forTIMESTAMP
, and for at most oneTIMESTAMP
column per table.
TIMESTAMP
andDATETIME
columns have no automatic properties unless they are specified explicitly, with this exception: If theexplicit_defaults_for_timestamp
system variable is disabled, the firstTIMESTAMP
column has bothDEFAULT CURRENT_TIMESTAMP
andON UPDATE CURRENT_TIMESTAMP
if neither is specified explicitly.
... -
根据文档的介绍,禁止这种自动模式有两种方式:
- 将
explicit_defaults_for_timestamp
的值设置为ON; - 用DEFAULT子句该该列指定一个默认值,无论默认值是什么,只要手动在SQL中指定,就不会默认出现自动更新的情况;
- 将
而且,根据文档,在MySQL 5.6.5版本之前,自动初始化更新只适用于TIMESTAMP,而且一张表中,仅允许第一个TIMESTAMP字段采用该特性。从MySQL 5.6.5开始,自动初始化更新同时适用于TIMESTAMP和DATETIME,且没有数量限制;更多的请查看原文研究;