MySQL查询以获取所有用户的最新条目

时间:2014-08-25 22:30:01

标签: mysql sql

我想获取所有个人用户的最新值。我有一张如下表所示的表格:

| id | userId | value | createdAt
1      20        1        2014-01-01
2      21        2        2014-01-05
3      20        1.5      2014-01-06
4      21        1.1      2014-01-08

我想要的输出是:

| id | userId | value | createdAt
3      20        1.5      2014-01-06
4      21        1.1      2014-01-08

我当前的Mysql查询如下所示:

SELECT * 
FROM  userTable
GROUP BY userId
ORDER BY createdAt DESC 

但是这个查询并没有解决问题,因为Group By似乎正在将用户的第一个条目与其所有后续用户ID分组。

然后我尝试了:

SELECT * 
FROM (SELECT * FROM userTable ORDER BY createdAt DESC) t 
GROUP BY userId

这返回了我预期的结果,但它似乎是一个非常次优的解决方案。我预计该表会大幅增长,那么有更好的查询吗? “更好”,因为速度更快。

感谢。

3 个答案:

答案 0 :(得分:2)

您可以使用子查询:

select id, userid, value, createdat
  from usertable x
 where createdat =
       (select max(y.createdat) from usertable y where y.userid = x.userid)

或加入内联视图:

select x.*
  from usertable x
  join (select userid, max(createdat) as lastcreatedat
          from usertable
         group by userid) y
    on x.userid = y.userid
   and x.createdat = y.lastcreatedat

答案 1 :(得分:0)

您需要创建一个子查询以获取与UserID分组的max createdAt值,然后使用子查询作为第二个表创建一个INNER JOIN。

SELECT a.id, a.suerId, a.[value], a.createdAt
FROM userTable a 
INNER JOIN (SELECT UserID, MAX(createdAt) AS MaxCreatedAt FROM userTable b GROUPBY UserID) b
ON b.MaxCreatedAt = a.createdAt AND b.UserID = a.UserID

答案 2 :(得分:0)

您可以尝试:

SELECT t1.*
FROM Table1 t1
LEFT JOIN Table1 t2
ON t2.userID = t1.userID
AND t2.createdAt > t1.createdAt
WHERE t2.id is null