我们经常遇到类似这样的需求,查询最近N秒、N分钟、N小时的数据及N天的数据,相关的方法和函数很多,本人最近用的MySQL数据库,也就用MySQL为例,大概介绍几种比较通用的方法。
一、查询最近N秒、N分钟、N小时、N天的数据
1. 查询最近N秒的数据
法一(推荐):
-- 查询最近300秒的数据
SELECT t.alarm_id, t.alarm_status, t.busi_type_name, t.begin_time
FROM alarm_list_info_view t
where t.begin_time between date_sub(now(),interval 300 SECOND) and now();
法二:
-- 查询最近300秒的数据
SELECT t.alarm_id, t.alarm_status, t.busi_type_name, t.begin_time
FROM alarm_list_info_view t
where TIMESTAMPDIFF(SECOND, t.begin_time, NOW()) > 0
and TIMESTAMPDIFF(SECOND, t.begin_time, NOW()) < 300;
2. 查询最近N分钟的数据
法一
-- 查询最近5分钟的数据
SELECT t.alarm_id, t.alarm_status, t.busi_type_name, t.begin_time
FROM yusys_aiops_alarm.alarm_list_info_view t where t.begin_time
between date_sub(now(), interval 5 MINUTE) and now();
法二
-- 查询最近5分钟的数据 包含当前分钟 <= 5 不包含