2012-03-26 79 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