2012-08-06 76 views
-1

我有以下表SQL GROUP BY和MAX()不會得到正確的結果

mes_id | user_a | user_b | message | room | time 
------------------------------------------------------ 
1  | 23  | 24  | hello | 1 | 5676766767 

user_aroom1

發送messageuser_b我想要得到的所有的最後爲每個房間的特定用戶(例如user_b)收到的消息,我嘗試了幾個查詢,但沒有找到正確的。

該解決方案並沒有爲我工作:sql_group_by_max

更新

我使用5.5.18 MySQL服務器

確定

這給我的結果,感謝

SELECT * 
FROM messeges C 
JOIN (
     SELECT room, user_a, MAX(messeges.date) AS max_time 
     FROM messeges 
     GROUP BY room, user_a 
    )a 
ON a.room = c.room 

AND a.user_a = c.user_a 
AND a.max_time = c.date 

WHERE c.user_b = '396' 
+1

你可以添加幾個疑問? – hims056 2012-08-06 08:04:59

+0

請添加您嘗試的查詢。我們更容易找出它出錯的地方。 – Bazzz 2012-08-06 08:06:39

+0

你正在使用什麼數據庫系統? – 2012-08-06 08:14:37

回答

1

試試這個:

select * from chat C join 
(select room,user_b,MAX([time]) as max_time 
from chat 
group by room,user_b)a 
on a.room=c.room 
and a.user_b=c.user_b 
and a.max_time=c.[time] 

如果你想多行,(在SQL Server)

with cte as (select *,ROW_NUMBER() 
    over (partition by room,user_b order by [time] desc) as rownum from chat) 
select * from cte order by rownum 
+0

嗨喬非常感謝你,我試過了,它沒有工作,我使用MySQL數據庫和表名稱是messeges SELECT * FROM messeges C JOIN( SELECT room,user_b,MAX(messeges.date)AS MAX_TIME FROM內留言 GROUP BY室,USER_B )一個ON a.room = c.room AND a.user_b = c.user_b AND a.max_time = c.date WHERE c.user_b = '396' – Crimeira 2012-08-06 08:23:50

+0

@克里斯蒂拉:它應該工作,你的桌子上是否有user_b ='396'? – 2012-08-06 08:28:04

+0

是的我想要一個特定用戶的結果,就像只有房間的Facebook私人消息,所以登錄的用戶只能查看每個用戶的最後一條消息。我也嘗試了第二個答案,但它沒有工作一些我得到語法錯誤我的表名稱是消息,時間字段是日期。非常感謝喬 – Crimeira 2012-08-06 09:07:46

0

試試這個:

Select * 
FROM chat a 
INNER JOIN (Select user_a, user_b , room ,MAX(time) as max_time 
    FROM chat 
    group by user_a, user_b , room) b on a.user_a=b.user_a and a.user_b=b.user_b and a.room=b.room 
+0

非常感謝你伊拉尼我想SELECT * FROM內留言一 INNER JOIN( SELECT USER_A,USER_B,房間,MAX(DATE)AS MAX_TIME 從內留言 GROUP BY USER_A,USER_B,房間 ) b ON a.user_a = b.user_a AND a.user_b = b.user_b AND aroomroom = b.room WHERE b.user_b ='396'並且我得到的重複行不是每個用戶的唯一空間,user_a和最後一條消息(我也嘗試了a.user_b) – Crimeira 2012-08-06 08:37:54