【Mysql】分组后获取最近的一条数据

发布时间 2023-08-10 13:03:45作者: rongbu2

分组后获取最近的一条数据
效果如下:

  1. 左连接后过滤
SELECT
    a.num,a.test_id,b.num,b.test_id
FROM
    test1 a
    LEFT JOIN test1 b ON a.test_id = b.test_id
    AND a.num < b.num
where
    b.num is null
  1. 使用max函数获取 时间戳最大的数据
SELECT
	max( num ) AS num,
	test_id 
FROM
	test1 
GROUP BY
	test_id
  1. 使用子查询,order by 后 limit 99999 很大的数 ,然后再group by。。歪门邪道
SELECT
    * 
FROM
    ( SELECT * FROM test1 ORDER BY num DESC LIMIT 1000 ) AS t 
GROUP BY
    test_id
  1. 使用开窗函数 mysql8