mysql各种时间查询

时间:2024-02-25 09:04:07
查询时间间隔:
DATE(create_time) < DATE_SUB(CURDATE(), INTERVAL 1 DAY);
DATE(create_time) < DATE_SUB(CURDATE(), INTERVAL 7 month);
createtime < DATE_SUB(NOW(),INTERVAL 5 MONTH) 
根据时间分类排序:
/*按天统计*/
GROUP BY DATE(create_time) ORDER BY DATE(create_time) DESC;


/*按周统计*/

GROUP BY WEEK(create_time) ORDER BY WEEK(create_time) DESC;


/*按月统计*/

GROUP BY MONTH(create_time) ORDER BY MONTH(create_time) DESC;


/*按季度统计*/

GROUP BY QUARTER(create_time) ORDER BY QUARTER(create_time) DESC;

/*按年统计*/

GROUP BY YEAR(create_time) ORDER BY YEAR(create_time) DESC;
/*查年示例写法*/
YEAR(createtime) YEAR

只查询年、月、日、小时、分钟或者组合查询:
格式:EXTRACT(unit FROM date)
unit支持的格式如下:
MICROSECOND, 
SECOND,  
MINUTE, 
HOUR, 
DAY, 
WEEK, 
MONTH, 
QUARTER, 
YEAR, 
DAY_MICROSECOND, 
HOUR_MICROSECOND, 
MINUTE_MICROSECOND, 
SECOND_MICROSECOND, 
DAY_HOUR, 
DAY_MINUTE, 
HOUR_MINUTE, 
DAY_SECOND, 
HOUR_SECOND, 
MINUTE_SECOND, 
YEAR_MONTH

获取当前时间
yyyy-mm-dd hh:mm:ss - now()
yyyy-mm-dd hh:mm:ss     - curdate()
yyyy-mm-dd hh:mm:ss     - curtime()

按小时分组查询
GROUP BY DATE_FORMAT( CREATETIME, \'%Y-%m-%d %H\' )

日期相减计算天数
TO_DAYS(日期)-TO_DAYS(日期)