获取当前时间开始的正确方法是:
SUBDATE(SUBDATE(SUBDATE(NOW(),
INTERVAL EXTRACT(MICROSECOND FROM NOW()) MICROSECOND),
INTERVAL EXTRACT(SECOND FROM NOW()) SECOND),
INTERVAL EXTRACT(MINUTE FROM NOW()) MINUTE))
所以要获得一个完整的小时范围,你会做类似的事情
SUBDATE(SUBDATE(SUBDATE(SUBDATE(NOW(),
INTERVAL EXTRACT(MICROSECOND FROM NOW()) MICROSECOND),
INTERVAL EXTRACT(SECOND FROM NOW()) SECOND),
INTERVAL EXTRACT(MINUTE FROM NOW()) MINUTE),
INTERVAL 1 HOUR) <= my_date
AND my_date < SUBDATE(SUBDATE(SUBDATE(NOW(),
INTERVAL EXTRACT(MICROSECOND FROM NOW()) MICROSECOND),
INTERVAL EXTRACT(SECOND FROM NOW()) SECOND),
INTERVAL EXTRACT(MINUTE FROM NOW()) MINUTE)
这实际上非常痛苦,如果您不太了解数据类型的纯度,您将使用格式化技巧来获取当前时间:
STR_TO_DATE(DATE_FORMAT(NOW(), '%Y%m%d%H'), '%Y%m%d%H') <= my_date
AND my_date <= ADDDATE(STR_TO_DATE(DATE_FORMAT(NOW(), '%Y%m%d%H'), '%Y%m%d%H'), INTERVAL 1 HOUR)
和前一小时:
SUBDATE(STR_TO_DATE(DATE_FORMAT(NOW(), '%Y%m%d%H'), '%Y%m%d%H'), INTERVAL 1 HOUR) <= my_date
AND my_date < STR_TO_DATE(DATE_FORMAT(NOW(), '%Y%m%d%H'), '%Y%m%d%H')
当天:
STR_TO_DATE(DATE_FORMAT(NOW(), '%Y%m%d'), '%Y%m%d') <= my_date
AND my_date <= ADDDATE(STR_TO_DATE(DATE_FORMAT(NOW(), '%Y%m%d'), '%Y%m%d'), INTERVAL 1 DAY)
和前一天:
SUBDATE(STR_TO_DATE(DATE_FORMAT(NOW(), '%Y%m%d'), '%Y%m%d'), INTERVAL 1 DAY) <= my_date
AND my_date < STR_TO_DATE(DATE_FORMAT(NOW(), '%Y%m%d'), '%Y%m%d')
当月:
STR_TO_DATE(DATE_FORMAT(NOW(), '%Y%m'), '%Y%m') <= my_date
AND my_date <= ADDDATE(STR_TO_DATE(DATE_FORMAT(NOW(), '%Y%m'), '%Y%m'), INTERVAL 1 MONTH)
和上个月:
SUBDATE(STR_TO_DATE(DATE_FORMAT(NOW(), '%Y%m'), '%Y%m'), INTERVAL 1 MONTH) <= my_date
AND my_date < STR_TO_DATE(DATE_FORMAT(NOW(), '%Y%m'), '%Y%m')