我很难尝试提出一个查询来解决我的问题,这就是我的架构基本上是
CREATE TABLE Attempts (
`login` varchar(25) DEFAULT NULL,
`date` datetime DEFAULT NULL,
`success` tinyint(1) DEFAULT '0'
);
我的数据看起来像这样
_______________________________________
| login | date |success|
+-------+---------------------+-------+
| user1 | 2017-12-12 12:00:00 | 0 |
| user1 | 2017-12-12 12:01:00 | 0 |
| user1 | 2017-12-12 12:03:00 | 0 |
| user1 | 2017-12-12 12:05:00 | 1 |
| user2 | 2017-12-12 12:00:00 | 0 |
| user2 | 2017-12-12 12:00:00 | 0 |
| user2 | 2017-12-12 12:00:00 | 0 |
+-------+---------------------+-------+
鉴于这些数据,我需要弄清楚用户是否曾在15分钟内尝试过10次或更多次失败。因此对于2017-12-12 12:00:00
我需要COUNT()
所有不成功的尝试,直到2017-12-12 12:15:00
和2017-12-12 12:01:00
我会计算所有尝试,直到2017-12-12 12:16:00
我尝试了像
这样的自我加入SELECT
a1.date, GROUP_CONCAT(a2.date)
FROM Attempts as a1
JOIN Attempts as a2
ON TIMESTAMPDIFF(MINUTE, a2.date, a1.date) BETWEEN 0 AND 15
GROUP BY a1.date;
但这似乎不正确,我觉得我过去已经解决了这个问题,目前解决方案正在逃避。
提前感谢您的帮助
答案 0 :(得分:0)
你非常接近。使用您的方法:
SELECT a1.date, COUNT(*)
FROM Attempts a1 JOIN
Attempts a2
ON TIMESTAMPDIFF(MINUTE, a2.date, a1.date) BETWEEN 0 AND 15
WHERE a2.success = 0
GROUP BY a1.date
HAVING COUNT(*) >= 10;
编辑:
您似乎希望按login
:
SELECT a1.login, a1.date, COUNT(*)
FROM Attempts a1 JOIN
Attempts a2
ON a1.login = a2.login and
TIMESTAMPDIFF(MINUTE, a2.date, a1.date) BETWEEN 0 AND 15
WHERE a2.success = 0
GROUP BY a1.login, a1.date
HAVING COUNT(*) >= 10;
Here是SQL小提琴。