查询存在最大(日期)的记录

Query for Records Where Exists Having Max(Date)

我正在尝试创建一个查询来查找具有至少一条日期小于 20 分钟

的记录的线程

这是心跳table,看起来像这样:

+--------------+-----------+---------------------+---------------------+
| 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

如果您想要线程在 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 table,那么你可以利用 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)
)

INTERVAL - 20 MINUTE

中删除 -