如何使用Group by语句从表中选择最新记录

时间:2015-04-26 06:39:23

标签: php mysql sql

我根据发件人ID

从表和组中获取聊天消息

消息表

msg_id     msg(messages)  sender(user id)  receiver (user id)  time (timestamp)
------------------------------------------------------------------------------
 1              hello bro             1              2                 12am
 2              hello                 2              1                 12am
 3              i disscuss something  1              2                 12:01am
 4              are you free          1              2                 12:03am

-----------------------------------------------------
**User Table**
-----------------------------------------------------
 u_id       user_name    
  1           khalid
  2           brain
  3           abdullah

然后当我进行此查询时

SELECT sender.user_name sender, receiver.user_name receiver,
       messages.time msgtime, messages.msg msg,sender.u_id u_id,
       sender.user_name user_name FROM messages LEFT JOIN user 
       AS sender ON messages.sender = sender.u_id LEFT JOIN user
       AS receiver ON messages.receiver = receiver.u_id where 
       sender.u_id<>1 group by messages.sender ORDER BY 
       messages.msg_id desc

但是当我使用发件人分组时,它不会在显示旧记录的分组语句中显示最新消息

我想要什么

我希望查询显示每个发件人的最新消息

4 个答案:

答案 0 :(得分:2)

您可以在不进行分组的情况下执行此操作 - 只需将left joining消息表添加到自身,谓词是相同的发件人,然后是时间戳。如果没有以后的时间戳,您将在第二个表中以空值结束,这意味着您已识别出最新的消息。

select s.user_name as `from`, r.user_name as `to`, m1.msg, m1.time 
  from messages m1
    left join messages m2
      on m1.time < m2.time and m1.sender = m2.sender
    inner join users s
      on m1.sender = s.u_id
    inner join users r
      on m1.receiver = r.u_id
  where m2.sender is null;

如果您绝对想要使用group by,可以先为每个发件人找到max(time),然后将该结果加回到messages和users表中,如下所示:

select s.user_name as `from`, r.user_name as `to`, m.msg, m.time
  from messages m
    inner join users s
      on m.sender = s.u_id
    inner join users r
      on m.receiver = r.u_id
    inner join (
      select sender, max(`time`) as ts
        from messages
        group by sender
    ) q on m.sender = q.sender and m.time = q.ts

两个查询都会给你相同的结果

答案 1 :(得分:0)

你约会desc order选择它。ORDER BY messages.timestamp desc

答案 2 :(得分:-2)

SELECT sender.user_name sender, receiver.user_name receiver,MAX(messages.time) msgtime, messages.msg msg,sender.u_id u_id,sender.user_name user_name 
FROM messages 
INNER JOIN user AS sender 
ON messages.sender = sender.u_id 
INNER JOIN user AS receiver 
ON messages.receiver = receiver.u_id 
where sender.u_id<>1 
group by messages.sender 
ORDER BY messages.msg_id desc

答案 3 :(得分:-2)

首先从此查询中选择最近的消息

SELECT sender, receiver, MAX(time) AS Most_Recent 
                                    FROM Messages WHERE receiver = receiverid(userid that receive this msg) GROUP BY sender 

根据最近的发件人信息

了解此查询给出的分组