简体   繁体   中英

How can this SQL query be more efficient?

mysql 5.7 linux

The query below takes about 210 seconds on 9000 records. Not really desirable performance.

The data table has these fields:

login_attempt_id integer
user_id integer
login_attempt_data datetime
login_attempt_ip string`

I wish to query the data to find the number of IPs that have failed login. For example:

109 119.27.191.202
93  118.25.146.128
83  132.232.31.117
81  132.232.160.234

The query:

select count(t0.login_attempt_ip) as `ip_count`, t0.login_attempt_ip 
  from sohne_sma_v4.wp_login_fails t0
  where t0.login_attempt_ip in
  (select distinct t1.login_attempt_ip from sohne_sma_v4.wp_login_fails t1
    where 20 <
    (select count(t2.login_attempt_ip) from sohne_sma_v4.wp_login_fails t2
       where t2.login_attempt_ip like t1.login_attempt_ip
    )
  )
  and datediff(now(), t0.login_attempt_date) < 15
  group by t0.login_attempt_ip
  order by ip_count desc;

I can guess the time is spent in the two inner queries.

What is a better way to achieve this query?

You dont really need all these subqueries.

You can just user GROUP BY...HAVING to keep grouped items having count more than 20.

Something like this should work

https://www.db-fiddle.com/f/vCMPWJaRxeSPVVDNSPVhcD/0

SELECT COUNT(t.login_attempt_id) AS ip_count,t.login_attempt_ip  FROM sohne_sma_v4.wp_login_fails t 
WHERE datediff(now(), t.login_attempt_date) < 15
GROUP BY t.login_attempt_ip HAVING (ip_count> 20 )
ORDER BY ip_count DESC;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM