鉴于我的以下表结构:
我正在尝试构建一个查询,该查询将返回失败登录尝试次数每个IP 的数量,因为过去一小时内同一IP上次成功登录。
例如,您会注意到过去一小时内单个IP中有多次尝试失败(0)
,但自上次成功登录(#145)以来,只有1次(#146),是我想要的回报。
此查询也应该是动态的,并返回分组IP的行。
到目前为止,这就是我所拥有的,但我认为@ipa
正在返回NULL
SELECT COUNT(*) tries, @ipa := login_ip
FROM login_log
WHERE login_id > (
SELECT MAX(login_id)
FROM login_log
WHERE login_success = 1
AND login_ip = @ipa
)
AND login_success = 0
AND login_date > NOW() - 3600
GROUP BY login_ip
ORDER BY tries DESC;
由于
答案 0 :(得分:2)
对表格进行别名并以这种方式进行尝试,因为@ipa
变量对您无效:
SELECT COUNT(1) tries, l.login_ip
FROM login_log l
WHERE login_id > (
SELECT MAX(login_id)
FROM login_log l2
WHERE l2.login_success = 1
AND l2.login_ip = l.login_ip
)
AND login_success = 0
AND login_date > NOW() - 3600
GROUP BY login_ip
ORDER BY tries DESC;
此外,您可以使用join
:
select
count(1) tries,
log1.login_ip
from
login_log log1
inner join (
select
login_ip,
max(login_date) as max_date
from
login_log
where
login_success = 1
group by
login_ip
) log2 on
log1.login_ip = log2.login_ip
where
log1.login_success = 0
and log1.login_date > NOW() - 3600
and log1.login_date > log2.max_date
group by
login_ip
order by tries desc
你可以尝试两种方式,看看哪种方式更快。</ p>