[英]MySQL query to get most recent entry for all users
我想獲取所有個人用戶的最新值。 我有一個表格,如下所示:
| 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
這返回了我預期的結果,但這似乎不是一個非常理想的解決方案。 我預計表格會大幅增長,因此是否有更好的查詢? “更好”,如更快。
謝謝。
您可以使用子查詢:
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
您需要創建一個子查詢以獲取與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
你可以試試:
SELECT t1.*
FROM Table1 t1
LEFT JOIN Table1 t2
ON t2.userID = t1.userID
AND t2.createdAt > t1.createdAt
WHERE t2.id is null
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.