-1

我有下表

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

user_a发送messageuser_b一个room 1

我想获取每个房间特定用户(例如 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'
4

2 回答 2

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
于 2012-08-06T08:12:49.550 回答
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
于 2012-08-06T08:18:39.143 回答