MySQL:获取最新的logging
在下面的表格中,如何根据login列而不是全部3条logging得到最近的id=1
的logging?
+----+---------------------+---------+ | id | signin | signout | +----+---------------------+---------+ | 1 | 2011-12-12 09:27:24 | NULL | | 1 | 2011-12-13 09:27:31 | NULL | | 1 | 2011-12-14 09:27:34 | NULL | | 2 | 2011-12-14 09:28:21 | NULL | +----+---------------------+---------+
使用聚合MAX(signin)
按ID分组。 这将列出每个id
最近signin
。
SELECT id, MAX(signin) AS most_recent_signin FROM tbl GROUP BY id
要获得整个单个logging,对每个id仅返回MAX(signin)
的子查询执行INNER JOIN
。
SELECT tbl.id, signin, signout FROM tbl INNER JOIN ( SELECT id, MAX(signin) AS maxsign FROM tbl GROUP BY id ) ms ON tbl.id = ms.id AND signin = maxsign WHERE tbl.id=1
SELECT * FROM tbl WHERE id = 1 ORDER BY signin DESC LIMIT 1;
显而易见的索引是(id)
,或者是(id, signin DESC)
上的多列索引 。
基于@ xQbert的答案,你可以避免子查询,使其通用性足以通过任何ID进行过滤
SELECT id, signin, signout FROM dTable INNER JOIN( SELECT id, MAX(signin) AS signin FROM dTable GROUP BY id ) AS t1 USING(id, signin)
Select [insert your fields here] from tablename where signin = (select max(signin) from tablename where ID = 1)
SELECT * FROM (SELECT * FROM tb1 ORDER BY signin DESC) GROUP BY id;