我有一个非常简单的表格:
+----------+--------------+------+-----+---------+-------+
| 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 | | |
+----------+--------------+------+-----+---------+-------+
我正在寻找一些特定的用户,我想要一个登录计数和最近的登录(如果存在任何登录)。我尝试过“GROUP BY”的各种组合,但没有任何工作。
我的简单计数查询是这样的:
mysql> SELECT count(*), username FROM logins WHERE username='foo@bar.com' and failed='0' group by username;
如何才能获得包含计数和上次登录的单行?
如果将时间戳转换为人性化格式,则获得积分。
编辑:第一个答案似乎对我来说最清楚,而且运作良好。
我也想出了这个,它似乎可以工作并在大约相同的时间内返回,但我不确定我在那里使用嵌套的SELECT做什么:
SELECT COUNT(*), username (SELECT MAX(time)) FROM logins WHERE username='foo@bar.com' AND failed='0' GROUP BY username;
要获得人类可读的时间:
SELECT COUNT(*), username (SELECT FROM_UNIXTIME(MAX(time))) FROM logins WHERE username='foo@bar.com' AND failed='0' GROUP BY username;
这个版本和第一个答案中看起来更合适的查询大约需要2m 27s(该表有大约161M行)。
答案 0 :(得分:2)
Max(time)
将为您提供最新的登录时间。请参阅下面的完整查询
SELECT username,
COUNT(*) AS `count`,
Max(`time`) AS `latest`
FROM logins
WHERE username = 'foo@bar.com'
AND failed = '0'
GROUP BY username;
答案 1 :(得分:0)
尝试以下:
SELECT count(*), username,time
FROM logins
WHERE username='foo@bar.com' and failed='0'
group by username
order by time desc
OR
SELECT count(*), username,max(time)
FROM logins
WHERE username='foo@bar.com' and failed='0'
group by username
答案 2 :(得分:0)
select username, count(username) count, max(time) time
from logins where username in ("a","b") group by username