【问题标题】:sql Group by and max() doesn't get the right resultssql Group by 和 max() 没有得到正确的结果
【发布时间】:2012-08-06 08:01:34
【问题描述】:

我有下表

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

user_aroom 1 中为user_b 发送了message

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

【问题讨论】:

  • 你能添加那几个查询吗?
  • 请添加您尝试过的查询。我们更容易发现问题所在。
  • 你使用的是什么数据库系统?

标签: mysql sql group-by max


【解决方案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

【讨论】:

  • 嗨,乔,非常感谢,我试过了,但没有用,我使用的是 mysql db,表名是 messeges SELECT * FROM messeges C JOIN ( SELECT room, user_b, MAX( messeges. date ) AS max_time FROM messeges GROUP BY room, user_b )a ON a.room = c.room AND a.user_b = c.user_b AND a.max_time = c.date WHERE c.user_b = '396'
  • @Crimeira:应该可以,你的桌子上有 user_b = '396' 吗?
  • 是的,我想要特定用户的结果,它就像 facebook 私人消息只有房间,所以登录的用户只能查看每个用户的最后一条消息。我也尝试了第二个答案,但它没有工作有些我得到语法错误我的表名是消息,时间字段是日期。非常感谢乔
【解决方案2】:

试试这个:

   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

【讨论】:

  • 非常感谢 irani 我试过 SELECT * FROM messeges a INNER JOIN (SELECT user_a, user_b, room, MAX(DATE) AS max_time FROM messeges 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 WHERE b.user_b = '396' 我得到每个用户的重复行,而不是唯一的房间,user_a 和最后一条消息(我也试过其中 a.user_b)
猜你喜欢
  • 2018-01-24
  • 1970-01-01
  • 2010-11-20
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多