获取给定 ID 的最新行

2021-11-20 00:00:00 sql mysql greatest-n-per-group

在下表中,如何根据 signin 列仅获取 id=1 的最近行,而不是全部 3 行?

In the table below, how do I get just the most recent row with id=1 based on the signin column, and not all 3 rows?

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

推荐答案

使用按 id 分组的聚合 MAX(signin).这将列出每个 id 的最新 signin.

Use the aggregate MAX(signin) grouped by id. This will list the most recent signin for each id.

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

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

To get the whole single record, perform an INNER JOIN against a subquery which returns only the MAX(signin) per 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

相关文章