MySQL GROUP BY最新的一些字段

时间:2011-08-12 09:03:20

标签: mysql group-by

我有一张这样的表:

ID    Type   UserID    Timestamp    
1     1      1000      1312389223
2     1      1000      1312389220
3     2      1000      1312389215
4     3      1000      1312389213
5     3      2000      1312389205
6     1      2000      1312389201
7     2      1000      1312389190

我现在需要的是仅检索此表中数据的某些部分。该列表显示了某个用户在我的网站上所做的事情的数据。 一些“类型”需要显示所有条目。其他人只需要有最新的显示。

在上面的示例中,我需要显示Type = 2的所有出现,但只显示Type = 1的top 1(按Timestamp排序)。 Type = 3也是如此。这是基于UserID的。

希望我已经清楚地解释了自己。

先谢谢你的帮助, 费。

2 个答案:

答案 0 :(得分:0)

select ID, 
       type, 
       userid, 
       max(timestamp)
from table
where type in (1, 3)
group by id, type, userid
union
select *
from table
where type = 2

答案 1 :(得分:0)

如果您不需要ID,简单快捷的解决方案

select user, type, timestamp from Table where type = 2
union
select user, type, max(timestamp) from Table where type in (1,3) group by user, type

这将保留ID,但它更复杂,有点慢:

select * from Table where type = 2
union
select * 
from Table t
join (
    select type, user, max(timestamp) as timestamp
    from Table 
    where type in (1,3)
    group by type, user
) tt on tt.user = t.user and tt.type=t.type and tt.timestamp = t.timestamp

无论如何,这两种解决方案都不是很可扩展