2014-02-05 44 views
0

我有一个表是这样的:MySQL的选择组合,并与最新的时间戳

+----+----+---------------------+---------------+ 
|lid |uid |timestamp   |token   | 
|----+----+---------------------+---------------+ 
| 10 | 10 | 2014-02-03 12:17:18 | 52efcf118a0ba | 
| 45 | 10 | 2014-02-03 12:51:13 | 52efd7046022d | 
| 20 | 10 | 2014-02-04 03:47:59 | 52f0a931d3945 | 
| 12 | 11 | 2014-02-04 05:21:57 | 52f0bf389371b | 
| 34 | 11 | 2014-02-05 06:36:26 | 52f222384fe2d | 
| 12 | 11 | 2014-02-05 07:06:42 | 52f229500b403 | 
| 32 | 12 | 2014-02-04 05:21:57 | 52f0bf389371b | 
| 55 | 12 | 2014-02-05 06:36:26 | 52f222384fe2d | 
| 61 | 12 | 2014-02-05 07:06:42 | 52f229500b403 | 

盖和UID是外键和表不具有唯一列。

我想选择分组的uid BUT与最新的时间戳。例如,从上面的数据,我只希望这些行:

+----+----+---------------------+---------------+ 
|lid |uid |timestamp   |token   | 
|----+----+---------------------+---------------+ 
| 20 | 10 | 2014-02-04 03:47:59 | 52f0a931d3945 | 
| 12 | 11 | 2014-02-05 07:06:42 | 52f229500b403 | 
| 61 | 12 | 2014-02-05 07:06:42 | 52f229500b403 | 
+1

[为每组分组结果获取最多n条记录]的可能重复(http://stackoverflow.com/questions/12113699/get-top-n-records-for-each-group-of-grouped-results ) –

+0

谢谢。没有注意到这一点。我认为这对我有帮助。 –

回答

2

这里是MySQL的一个典型方式:

select t.* 
from table t 
where not exists (select 1 
        from table t2 
        where t2.uid = t.uid and 
         t2.timestamp > t.timestamp 
       ); 

的逻辑是:让我的所有行从表中,哪里有没有大于此时间戳的相同uid的时间戳。你应该有一个table(uid, timestamp)的性能指数。