I have a very simple table:
+----------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+-------+
| time | int(11) | YES | | 0 | |
| username | varchar(120) | NO | MUL | | |
| ip | varchar(40) | NO | MUL | | |
| failed | varchar(40) | NO | MUL | | |
+----------+--------------+------+-----+---------+-------+
I’m looking to query for a few specific users and I want both a count of logins and the most recent login (if any logins exist). I’ve tried various combinations of “GROUP BY” and nothing is quite working.
My simple count query is this:
mysql> SELECT count(*), username FROM logins WHERE username='foo@bar.com' and failed='0' group by username;
How can I still get a single row back that contains both a count and the last login?
Bonus points if it turns the timestamp into human-friendly format.
edit: The first answer seems the clearest to me, and that worked well.
I also came up with this, which seems to work and returns in about the same amount of time, but I’m not sure what I’m doing there with the nested SELECT:
SELECT COUNT(*), username (SELECT MAX(time)) FROM logins WHERE username='foo@bar.com' AND failed='0' GROUP BY username;
And to get a human-readable time:
SELECT COUNT(*), username (SELECT FROM_UNIXTIME(MAX(time))) FROM logins WHERE username='foo@bar.com' AND failed='0' GROUP BY username;
Both this version and the more proper looking query in the first answer take about 2m 27s (the table has about 161M rows).
Max(time)will give you the latest login time. See the full query bellow