我正在尝试创建一个查询来查找至少有一条日期小于 20分钟的记录
的帖子这是一个看起来像这样的心跳表:
+--------------+-----------+---------------------+---------------------+
| heartbeat_id | server_id | thread | last_checkin |
+--------------+-----------+---------------------+---------------------+
| 3 | 133 | EscalationMonitor | 2016-03-16 23:46:07 |
| 7 | 133 | EmailMonitor | 2016-03-16 23:47:31 |
| 11 | 133 | TableMonitor | 2016-03-16 23:42:49 |
| 15 | 133 | NotificationMonitor | 2016-03-16 23:46:30 |
| 19 | 127 | EmailMonitor | 2016-03-16 23:47:21 |
| 23 | 127 | TableMonitor | 2016-03-16 23:46:11 |
| 27 | 127 | EscalationMonitor | 2016-03-16 23:47:58 |
| 31 | 127 | NotificationMonitor | 2016-03-16 23:41:10 |
| 35 | 123 | EmailMonitor | 2016-03-16 23:47:59 |
| 39 | 123 | TableMonitor | 2016-03-16 23:43:10 |
| 43 | 123 | EscalationMonitor | 2016-03-16 23:46:26 |
| 47 | 123 | NotificationMonitor | 2016-03-16 23:46:47 |
+--------------+-----------+---------------------+---------------------+
这就是我的位置,但这会搜索至少一条超过 20分钟的记录。
SELECT * FROM heartbeat h WHERE exists
(
select * from heartbeat h2
where last_checkin < date_add(now(), INTERVAL - 20 MINUTE)
)
group by thread
答案 0 :(得分:2)
如果您希望线程在20分钟前至少有1次检查,您可以将该条件放在where子句中并使用distinct来删除重复项:
select distinct thread from heartbeat
where last_checkin > date_sub(now(), INTERVAL 20 MINUTE)
要检索没有签到不到20分钟的所有线程:
select thread from heartbeat
group by thread
having count(case when last_checkin > date_sub(now(), INTERVAL 20 MINUTE) then 1 end) = 0
如果您有threads
表格,那么您可以利用not exists
select * from threads t where not exists (
select 1 from heartbeat h
where t.thread = h.thread
and h.last_checkin > date_sub(now(), INTERVAL 20 MINUTE)
)
答案 1 :(得分:0)
从-
INTERVAL - 20 MINUTE