https://www.begtut.com/mysql/mysql-row-number-function.html
https://zhuanlan.zhihu.com/p/225172589
在下表中按 username , number 分组后取 create_time 最新时间的数据记录。
原表数据:
期望结果:
方法1:根据 username , number 分组,同时取最新时间,再自关联查询
SELECT a.* FROM test_a AS a,
(
SELECT
username,
number,
max( create_time ) create_time
FROM test_a GROUP BY username, number
) AS b
WHERE a.create_time = b.create_time
AND a.username = b.username
AND a.number = b.number;
方法2:根据 username , number 分组,按create_time降序排,生成 row_number 序号后根据序列取记录。(MySQL 8.0以上版本使用,测试版本:8.0.17)
SELECT * FROM
(
SELECT
*,
ROW_NUMBER() over ( PARTITION BY username, number ORDER BY create_time DESC ) AS rn
FROM test_a
) AS t
WHERE rn = 1;
该方法会生成rn结果集如下图: