2011-08-12 38 views
0

我有這樣的一個表: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(按時間戳排序)。類型= 3也是如此。這是每個用戶ID的基礎。

希望我已經清楚地解釋了我自己。

在此先感謝您的幫助, 菲捨爾。

+0

到目前爲止你所得到的查詢是什麼? – 321X

+0

你需要所有這些在一個單一的查詢?你爲什麼不考慮把它們分開? – Vijay

+0

他們不需要在單個查詢中。我只是需要它儘可能快地運行:) – fischer

回答

0

簡單快捷的解決方案,如果你不需要標識

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 

不管怎樣,這兩種解決方案都不是很可擴展的

+0

非常感謝。我會看看這些。你有什麼想法我可以做出一個可擴展的解決方案嗎? – fischer

+0

只是不要在單個查詢中使用它。我認爲你的PHP代碼中可能有一個'base-query',比如$ base ='select * from Table',並且爲它添加​​條件:$ base。=「where type = 2」for type 2 or $ base。 =「where type = 1 and user = 1 limit 0,1」等 – J0HN

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 
+0

是不是「按ID,類型,用戶ID」會給每個記錄? – J0HN

+0

D'oh - 您的權利 –