如何从所有用户获取最新消息

时间:2014-11-24 13:59:21

标签: php mysql sql

我有两个表,一个用于用户,另一个用于消息我希望每个用户的最新消息发送给用户1,我的代码在下面

SELECT u.profile_pic
     , u.username
     , u.firstname
     , u.lastname
     , m.message_from
     , m.message_body 
  FROM user u
  JOIN messages m
    ON m.message_from = u.user_no 
 WHERE m.message_to = $userno
 ORDER 
    BY m.sent_time DESC

4 个答案:

答案 0 :(得分:1)

如果可以包含表结构(messages表中是否有唯一的ID?),那么给出答案会更容易。但是根据你问题中的信息,这应该有效:

SELECT 
  u.profile_pic,
  u.username,
  u.firstname,
  u.llastname,
  m.message_from,
  m2.message_body 
FROM  user u
JOIN (SELECT message_from,message_to,max(sent_time)
      FROM  messages
      GROUP BY message_from,message_to) m 
        ON user.user_no = messages.message_from 
        AND messages.message_to = '$userno'
JOIN messages m2 ON m.message_from = m2.message_from
                 AND m.message_to = m2.message_to
                 AND m.sent_time = m2.sent_time

基本上,子选择会将所有最新消息从一个用户提取到另一个用户,然后您将加入这些消息以过滤掉所有其他消息。

答案 1 :(得分:0)

使用LEFT JOIN在同一用户和更新的sent_time上发送消息表。每个用户的最新版本都没有这样的消息:

SELECT profile_pic,username,firstname,lastname,messages.message_from,messages.message_body 
FROM  user 
JOIN messages ON user.user_no = messages.message_from 
LEFT JOIN messages AS newermessages ON user.user_no = newermessages.message_from AND messages.sent_time < newermessages.sent_time
WHERE  messages.message_to = '$userno' 
AND newermessages.id IS NULL
ORDER BY messages.sent_time DESC

答案 2 :(得分:0)

来自每个用户的最新消息:

SELECT a.*
  FROM messages a
  JOIN 
     ( SELECT message_from
            , MAX(sent_time) max_sent_time 
         FROM messages 
        GROUP 
           BY message_from
     ) b
    ON b.message_from = a.message_from
   AND b.max_sent_time = a.sent_time;

这个问题的其余部分留给了读者。

答案 3 :(得分:-2)

尝试将ORDER BY子句的字段添加到您的选择中:

SELECT u.profile_pic
     , u.username
     , u.firstname
     , u.lastname
     , m.message_from
     , m.message_body 
     , m.sent_time
  FROM user u
  JOIN messages m
    ON m.message_from = u.user_no 
 WHERE m.message_to = $userno
 ORDER 
    BY m.sent_time DESC