2011-06-19 37 views
0

對於這個表:如何對此SELECT語句進行編碼?

mysql> describe activity; 
+---------------------------+-------------+------+-----+---------+-------+ 
| Field      | Type  | Null | Key | Default | Extra | 
+---------------------------+-------------+------+-----+---------+-------+ 
| user_id     | varchar(16) | NO |  | NULL |  | 
| login_time    | int(11)  | NO |  | NULL |  | 
| last_activity_time  | int(11)  | NO |  | NULL |  | 
| last_activity_description | text  | YES |  | NULL |  | 
| logout_time    | int(11)  | NO |  | NULL |  | 
+---------------------------+-------------+------+-----+---------+-------+ 
5 rows in set (0.01 sec) 

我想選擇最新last_activity_time(標準UNIX時間戳),誰是登錄每個用戶(即具有一個或多個行,其中logout_time不ZER0)。

我試圖

SELECT user_id, login_time, MAX(last_activity_time) 
    FROM activity 
WHERE logout_time="0"; 

...但是,發現只有兩個用戶單一入口登錄,可能是因爲我選擇了MAX(last_activity_time)

我要的是一樣的東西

SELECT all unique user_ids 
    SELECT each of those which has one or more entries where `logout_time` != 0 
    SELECT the maximum value of `logout_time` for each of those 

所有在一個單一的SELECT語句。我怎樣才能做到這一點?

回答

3
SELECT user_id, MAX(logout_time) 
FROM activity 
WHERE logout_time <> "0" 
GROUP BY user_id; 
+0

+1和答案。謝謝 – Mawg

相關問題