mysql为所有具有相同名称的人按日期选择最新

时间:2018-11-20 10:58:36

标签: mysql

我有一个用户点数表:

id, created_at, user_id, points
1, 2018-11-01, 1, 20
2, 2018-11-03, 1, 12
3, 2018-11-04, 2, 15
...

我现在想选择前50名用户,但仅考虑用户的最新分数。即用户1有两个条目,只有最新的(2018-11-03)应该计数。

预期结果:

id, created_at, user_id, points
3, 2018-11-04, 2, 15
2, 2018-11-03, 1, 12
...

2 个答案:

答案 0 :(得分:1)

Derived Table中,可以为每个created_at设置created_at(最新的user_id)的最大值。然后,您可以将此结果集加入主表,以仅获取对应于最新created_at的行。

现在,使用该结果集以降序对points进行排序,并使用LIMIT 50

仅考虑前50名。
SELECT t.*
FROM your_table AS t
JOIN
( SELECT
    user_id, MAX(created_at) AS latest_created_at 
  FROM your_table
  GROUP BY user_id 
) AS dt 
  ON dt.user_id = t.user_id AND 
     dt.latest_created_at = t.created_at 
ORDER by t.points DESC
LIMIT 50

答案 1 :(得分:0)

您可以尝试使用相关子查询

public class AnotherActor extends AbstractActor { ... }

// Inside MyActor#createReceive:
ActorSelection anotherActorSel = context().actorSelection("AnotherActor");

anotherActorSel.tell(new SomeMessage(), self());