MySQL: Get most recent record

后端 未结 7 1727
情歌与酒
情歌与酒 2020-11-28 20:42

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

+----+--         


        
7条回答
  •  情深已故
    2020-11-28 21:18

    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
    

    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
    

提交回复
热议问题