我有一个MySQL DB表,用于记录用户登录和注销活动。 我需要选择注销后20分钟内未重新登录的所有用户记录。
例如:表格:日志
ID | User | Event | Time
-----------------------------
1 | 1 | LOGIN | 10:00:00
2 | 2 | LOGIN | 10:05:00
3 | 3 | LOGIN | 10:15:00
4 | 1 | LOGOUT | 11:00:00
5 | 3 | LOGOUT | 11:01:00
6 | 2 | LOGIN | 12:20:00
7 | 2 | LOGOUT | 12:30:00
8 | 1 | LOGIN | 12:31:00
9 | 2 | LOGIN | 12:55:00
根据此样本表,必须显示在注销和登录之间超出间隔20分钟的用户。 用户1超过记录4和8之间的20分钟间隔 用户2超过记录7和9之间的20分钟间隔
这应该显示
ID | User
----------
4 | 1
8 | 1
7 | 2
9 | 2
如何编写查询以完成此操作?
答案 0 :(得分:1)
这回答了这个问题:
我需要选择注销后20分钟内未重新登录的所有用户记录。
select lo.*
from (select l.*,
(select min(l2.time)
from logs l2
where l2.user = l.user and l2.time > l.time and
l2.event = 'LOGIN'
) as next_login_time
from logs l
where l.event = 'LOGOUT'
) lo
where next_login_time > time + interval 20 minute;
您的样本结果包括登录结果。目前还不清楚如何根据您提出的问题来定义它们。
答案 1 :(得分:1)
如果两行相距20分钟,您似乎有兴趣获取两行。以下尝试模拟LEAD和LAG:
allow
或者,尝试以下似乎可行的方法,除了它将两行放在一起:
SELECT * FROM (
SELECT *, (
SELECT CASE WHEN EVENT = 'LOGOUT' AND main.Event = 'LOGIN' THEN TimeDIFF(main.Time, Time) END
FROM t AS prev
WHERE User = main.User AND Time < main.Time
ORDER BY Time DESC
LIMIT 1
) AS diff_lag, (
SELECT CASE WHEN EVENT = 'LOGIN' AND main.Event = 'LOGOUT' THEN TimeDIFF(Time, main.Time) END
FROM t AS next
WHERE User = main.User AND Time > main.Time
ORDER BY Time ASC
LIMIT 1
) AS diff_lead
FROM t AS main
) x
WHERE diff_lag > '00:20:00' OR diff_lead > '00:20:00'