2013-07-10 116 views
1

我有兩個表:聚合函數衝突

users: 
___________________________ 
|user_id  | username | 
|_______________|___________| 
| 1   | Dolly | 
| 2   | Didi  | 
|_______________|___________| 

forum: 
_____________________________________________________________ 
|match_static_id| comment | timpstamp   | user_id | 
|_______________|___________|______________________|__________| 
| 1   | Hi  | 2013-07-10 12:15:03 |  2 | 
| 1   | Hello | 2013-07-09 12:14:44 |  1 | 
|_______________|___________|______________________|__________| 

此查詢工作正常,它使用只是THW forum表:

SELECT forum.match_static_id, 
count(forum.match_static_id) 'comments_no', max(forum.timestamp)'timestamp' 
FROM forum 
GROUP BY forum.match_static_id 
Order BY timestamp DESC 

但是,下面的查詢使用兩個表:

SELECT forum.match_static_id, 
count(forum.match_static_id) 'comments_no', max(forum.timestamp)'timestamp', users.username 
FROM forum 
INNER JOIN users on users.id = forum.user_id 
GROUP BY forum.match_static_id 

在這裏我想得到的最大用戶(時間戳),但我得到了錯誤的用戶可以任何身體給我一個線索,請嗎? ORDER BY的時間戳降序

+1

你想的'MAX(時間戳)'的foreach'match_static_id '或什麼?那麼'users.username'你想爲每個分組的'match_static_id'選擇哪個用戶名呢? –

+0

我想要max(timestamp)的註釋的用戶名 – Basel

+1

這是一個常見問題 – Strawberry

回答

3

試試這個:

SELECT f1.match_static_id, 
    f2.comments_no, 
    f2.maxtimestamp, 
    users.username 
FROM forum AS f1 
INNER JOIN 
(
    SELECT match_static_id, 
    max(timestamp) maxtimestamp, 
    count(comment) AS comments_no 
    FROM Forum 
    GROUP BY match_static_id 
) AS f2 ON f1.match_static_id = f2.match_static_id 
     AND f1.timestamp = f2.maxtimestamp 
INNER JOIN users on users.user_id = f1.user_id; 

看到它在這裏的行動:

+0

但是,如果你看到演示的comment_no字段給1它應該是2.我需要max timestamp的用戶,但我也想comment_no不受影響 – Basel

+0

@BaselShbeb - 啊哈,好的抱歉,請參閱我的編輯。從內部查詢中選擇它。 –