通过eventid获取每个用户的最新记录

时间:2019-05-15 05:23:33

标签: mysql sql laravel

在以下数据库中,

   id      userid        eventid      created_at
    1         1            100      2010-01-01
    2         1            101      2010-02-01
    3         1            100      2010-03-01
    4         1            101      2010-04-01
    5         2            100      2010-05-01
    6         2            100      2010-06-01

我正在尝试基于eventid获取每个用户的最新活动,并给出如下输出:

6         2            100      2010-06-01
4         1            101      2010-04-01
3         1            100      2010-03-01

2 个答案:

答案 0 :(得分:4)

使用group byaggregation

select userid,envid,max(id) as id, max(created_at) as created_at
from tablename a
group by userid,envid

答案 1 :(得分:3)

使用行数

SELECT *
FROM (SELECT ROW_NUMBER() OVER (PARTITION BY userid, eventid ORDER BY id DESC) as RId,
             t.*
      FROM Tablename t
     ) T
WHERE RId = 1 ;