小编典典

MySQL:获取最新记录

mysql

在下表中,如何仅根据登录列获取的 最新记录id=1而不是所有3条记录?

+----+---------------------+---------+
| 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    |
+----+---------------------+---------+

阅读 1430

收藏
2020-05-17

共1个答案

小编典典

使用MAX(signin)按ID分组的汇总。这将列出signin每个最新的id

SELECT 
 id, 
 MAX(signin) AS most_recent_signin
FROM tbl
GROUP BY id

要获取完整的单个记录,请INNER JOIN对仅返回MAX(signin)每个ID 的子查询执行。

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
2020-05-17