2012-03-26 81 views
9

我有一個三列的MySQL表:用戶名,位置,時間戳。這基本上是用戶活動的日誌,他們在哪個位置以及他們在那裏的時間。SQL查詢select與最近的時間戳第一

我想要做的是選擇一個獨特的用戶名+位置,其中只提供最近的項目(通過時間戳)。

所以說,該表包括:

tom roomone 2011-3-25 10:45:00 
tom roomtwo 2011-3-25 09:00:00 
tom roomtwo 2011-3-25 08:30:00 
pam roomone 3011-3-25 07:20:23 

我想只有這些被選中:

tom roomone 2011-3-25 10:45:00 
tom roomtwo 2011-3-25 09:00:00 

回答

15

嘗試用表1爲你的表名以下查詢:

select username, location, max(timestamp) from table1 
group by username, location 
1

這個答案實際上並不能保證其他列與用戶名/時間戳具有相同的記錄,但以下內容將會是l(使用子查詢)。

select t1.* 
from (
    select ForeignKeyId,AttributeName, max(Created) AS MaxCreated 
    from YourTable 
    group by ForeignKeyId,AttributeName 
) t2 
join YourTable t1 
on t2.ForeignKeyId = t1.ForeignKeyId 
and t2.AttributeName = t1.AttributeName 
and t2.MaxCreated = t1.Created 

答發現在:

Select distinct most recent