在下表中,如何仅根据登录列获取的 最新记录 ,id=1而不是所有3条记录?
id=1
+----+---------------------+---------+ | 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分组的汇总。这将列出signin每个最新的id。
MAX(signin)
signin
id
SELECT id, MAX(signin) AS most_recent_signin FROM tbl GROUP BY id
要获取完整的单个记录,请INNER JOIN对仅返回MAX(signin)每个ID 的子查询执行。
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