https://www.begtut.com/mysql/mysql-row-number-function.html
    https://zhuanlan.zhihu.com/p/225172589

    在下表中按 username , number 分组后取 create_time 最新时间的数据记录。
    原表数据:
    image.png
    期望结果:
    image.png

    1. 方法1:根据 username , number 分组,同时取最新时间,再自关联查询

      1. SELECT a.* FROM test_a AS a,
      2. (
      3. SELECT
      4. username,
      5. number,
      6. max( create_time ) create_time
      7. FROM test_a GROUP BY username, number
      8. ) AS b
      9. WHERE a.create_time = b.create_time
      10. AND a.username = b.username
      11. AND a.number = b.number;
    2. 方法2:根据 username , number 分组,按create_time降序排,生成 row_number 序号后根据序列取记录。(MySQL 8.0以上版本使用,测试版本:8.0.17

      1. SELECT * FROM
      2. (
      3. SELECT
      4. *,
      5. ROW_NUMBER() over ( PARTITION BY username, number ORDER BY create_time DESC ) AS rn
      6. FROM test_a
      7. ) AS t
      8. WHERE rn = 1;

      该方法会生成rn结果集如下图:
      image.png