如何在SQL中获得频繁的时间间隔?

时间:2012-12-18 19:56:05

标签: mysql logging login

原谅我这个简单的问题,但我不是MySQL的专家。我需要从名为detailed_log的日志表创建一个报告模块。问题是我不知道如何经常列出登录错误的用户(比如少于5分钟)。

这里我按顺序列出我们所拥有的内容(我按时间简要排序并删除不必要的列)

SELECT user_name, 
time, 
SUBSTR(status, 1, 8) AS status 
FROM detailed_log 
WHERE (status LIKE '%LOGINERR%' OR status LIKE '%LOGINOK%') 
ORDER BY time

这是结果

result

所以有人可以说我如何列出每个用户的登录错误,间隔为< 5分钟?
编辑澄清我添加了以下示例:

enter image description here

1 个答案:

答案 0 :(得分:1)

通过将表连接到自己的表格,您可以获得LOGINERR,其中还有不到5分钟的LOGINERR。

SELECT l1.user_name, l1.time
FROM detailed_log AS l1
JOIN detailed_log AS l2 ON l2.user_name = l1.user_name
WHERE l1.status LIKE 'LOGINERR' AND l2.status LIKE 'LOGINERR'
AND l1.time > l2.time
AND l1.time < (l2.time + INTERVAL 5 MINUTE)

某些分组,您可以获得摘要:

SELECT l1.user_name, MAX(l1.time) AS latest, COUNT(DISTINCT l1.time) AS tries
FROM detailed_log AS l1
JOIN detailed_log AS l2 ON l2.user_name = l1.user_name
WHERE l1.status LIKE 'LOGINERR' AND l2.status LIKE 'LOGINERR'
AND l1.time > l2.time
AND l1.time < (l2.time + INTERVAL 5 MINUTE)
GROUP BY l1.user_name