我有一些日志表来记录代理所具有的每个有趣事件。基本上,如果它已记录或忙碌或其他什么。
话虽如此,想象一下:
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 ......)
我一直在想,但没找到诀窍。
有谁知道?
答案 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)
。