我有下表
mes_id | user_a | user_b | message | room | time
------------------------------------------------------
1 | 23 | 24 | hello | 1 | 5676766767
user_a
在message
user_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'
答案 0 :(得分: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
答案 1 :(得分: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