从日志表中选择最后一个操作

时间:2012-03-05 12:10:46

标签: mysql

我有一些日志表来记录代理所具有的每个有趣事件。基本上,如果它已记录或忙碌或其他什么。

话虽如此,想象一下:

    agent       event           dateTime
1   foo       logged        2012-03-01 14:23:36
2   foo       unlogged      2012-03-01 14:24:36
3   baz       logged        2012-03-01 14:25:36
4   bar       logged        2012-04-01 08:24:36
6   bar       unlogged      2012-04-01 08:25:36
7   foo       logged        2012-04-01 08:26:36

我想只检索“已登录”的那些,在这个例子中,它将是foo(id 7)和baz(id 3)(这里的obsesive worker ......)

我一直在想,但没找到诀窍。

有谁知道?

2 个答案:

答案 0 :(得分:2)

这应该可以通过NOT EXISTS

来实现
SELECT *
FROM log
WHERE NOT EXISTS (
  SELECT *
  FROM log l
  WHERE log.agent = l.agent
  AND l.event = 'unlogged'
  AND l.datetime > log.datetime
)

答案 1 :(得分:1)

<强>更新 * 再次更新以检索上次状态 *

SELECT a.* 
FROM table1 a
INNER JOIN 
(SELECT agent, 
 MAX(`dateTime`) as lastActionDt, 
 MAX(CASE WHEN `event`='logged' THEN `dateTime` END) as last_logged_in_event,
 MAX(CASE WHEN `event`='unlogged' THEN `dateTime` END) as last_logged_out_event 
 FROM table1 
 GROUP BY agent
 HAVING last_logged_out_event IS NULL OR last_logged_in_event>last_logged_out_event
) b ON
 (b.agent = a.agent AND b.lastActionDt = a.`dateTime`)

我认为如果没有相应的unlogged,就不可能有logged个事件。如果可能,那么HAVING应该看HAVING last_logged_in_event IS NOT NULL AND(last_logged_out_event IS NULL OR last_logged_in_event>last_logged_out_event)