Add these indexes:
alter table users_logins
add key (iplogin, userid, logindate),
add key (userid, logindate);
Now demonstrate that you can do the query to get the earliest login for each user by finding the login where there is no other earlier login for the same user.
This is a common solution to get the greatest/earliest entry per user or whatever.
select t1.iplogin, count(*) as numberofaccounts
from users_logins as t1
left outer join users_logins as t2
on (t1.userid=t2.userid and t1.logindate > t2.logindate)
where t2.userid is null
group by iplogin\G
The indexes defined above help the LEFT OUTER JOIN
and the GROUP BY
.
The EXPLAIN report shows that this is pretty well optimized. It makes use of indexes for both tables, and does not cause a temp table or filesort, which are frequently performance killers.
It does do an index-scan (type: index
) which means it reads the entire index, but at least that's not a table-scan.
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: t1
partitions: NULL
type: index
possible_keys: iplogin
key: iplogin
key_len: 29
ref: NULL
rows: 1
filtered: 100.00
Extra: Using index
*************************** 2. row ***************************
id: 1
select_type: SIMPLE
table: t2
partitions: NULL
type: ref
possible_keys: userid
key: userid
key_len: 5
ref: test.t1.userid
rows: 1
filtered: 100.00
Extra: Using where