我有一张桌子:
+------------+-----------------------------------------------------------------------------------+
| Field | Type |
+------------+-----------------------------------------------------------------------------------+
| id | int(10) unsigned |
| type | enum('REGISTER','ACTIVATE','LOGIN_SUCCESS','LOGIN_FAIL','LOGOUT','LOCK','UNLOCK') |
| user_id | int(10) unsigned |
| mod_id | int(10) unsigned |
| date | timestamp |
| ip | int(10) unsigned |
| user_agent | text |
+------------+-----------------------------------------------------------------------------------+
我试图以最简单的方式确定(最好只使用MySQL),如果自上一个type = LOGIN_FAIL
以来或从表开始以来有{3}个连续记录。
例如
type = LOGIN_SUCCESS
会在
时返回+----+---------------+---------+--------+---------------------+----+------------+
| id | type | user_id | mod_id | date | ip | user_agent |
+----+---------------+---------+--------+---------------------+----+------------+
| 6 | LOGIN_SUCCESS | 3 | NULL | 2012-07-21 14:08:32 | 0 | agent |
| 7 | LOGIN_FAIL | 3 | NULL | 2012-07-21 14:08:32 | 0 | agent |
| 8 | LOGIN_FAIL | 3 | NULL | 2012-07-21 14:08:32 | 0 | agent |
| 9 | LOGIN_FAIL | 3 | NULL | 2012-07-21 14:08:32 | 0 | agent |
+----+---------------+---------+--------+---------------------+----+------------+
TRUE
会返回+----+---------------+---------+--------+---------------------+----+------------+
| id | type | user_id | mod_id | date | ip | user_agent |
+----+---------------+---------+--------+---------------------+----+------------+
| 6 | LOGIN_FAIL | 3 | NULL | 2012-07-21 14:08:32 | 0 | agent |
| 7 | LOGIN_FAIL | 3 | NULL | 2012-07-21 14:08:32 | 0 | agent |
| 8 | LOGIN_SUCCESS | 3 | NULL | 2012-07-21 14:08:32 | 0 | agent |
| 9 | LOGIN_FAIL | 3 | NULL | 2012-07-21 14:08:32 | 0 | agent |
+----+---------------+---------+--------+---------------------+----+------------+
。是否可以通过简单的查询执行此操作,还是需要以某种脚本语言实现此检查?
编辑:我忘了提到这个查询必须限于某个user_id,但我认为这不会有问题。
否则,甚至更好,是否可以计算符合此条件的记录数(即自上次FALSE
以来存在多少连续type = LOGIN_FAILED
条记录)
答案 0 :(得分:2)
SELECT COUNT(*) FROM `table`
WHERE
id >
(IFNULL(
(SELECT id
FROM `table`
WHERE `type`='LOGIN_SUCCESS'
ORDER BY id DESC
LIMIT 1),0
)
AND `type`='LOGIN_FAIL'
将获得自上次成功以来失败的数量。
答案 1 :(得分:2)
希望这会对你有所帮助
SELECT IF(COUNT(a.id)>=3, TRUE, FALSE) AS fresult FROM last_login AS a,
(
SELECT COUNT( b.id ) AS cnt, MAX( b.id ) AS maxid FROM last_login AS b
WHERE b.login_type = 'LOGIN_SUCCESS'
) AS c
WHERE a.id>c.maxid OR c.cnt=0
GROUP BY a.login_type