Sql查询只显示特定用户的最新消息?

时间:2012-07-01 17:05:24

标签: mysql sql database

我有两个sql表,一个有用户,另一个有消息。 现在我的查询是:

SELECT users.memberid,users.username,users.profileimage,users.gender,message.messagebody, message.fromid,message.toid,message.messageid 
FROM message,users 
WHERE message.fromid = users.memberid AND message.toid = '$id' AND recieverdeleted='0' 
ORDER BY datetime DESC LIMIT 55

现在返回的是每个消息的所有信息,无论formid(发件人的id) 问题是,我想只显示每个来自id的最新消息。类似Facebook如何只显示朋友x发送给你的最新消息,而不是所有消息。在用户点击朋友的最新消息后,我将继续显示所有消息。 感谢

4 个答案:

答案 0 :(得分:1)

嗯,你试过了。那很好。

 SELECT u.memberid
      , u.username
      , u.profileimage
      , u.gender
      , m.messagebody
      , m.fromid
      , m.toid
      , m.messageid 
   FROM users u
   JOIN message m
     ON m.fromid = u.memberid
   JOIN (SELECT fromid,toid,MAX(datetime) max_datetime FROM message GROUP BY fromid,toid) n
     ON n.fromid = m.fromid
    AND n.toid = m.toid
    AND n.max_datetime = m.datetime
  WHERE message.toid = $id 
    AND recieverdeleted = 0 
  ORDER 
     BY datetime DESC LIMIT 55;

答案 1 :(得分:0)

首先join这两个表不是应用order by,因为此时命令不确定要应用排序的表。 或者更好的是,从两个表的选择中创建一个中间表,然后应用排序。 类似的东西:

SELECT username,messagebody,fromid FROM(
SELECT users.memberid,users.username,users.profileimage,users.gender,message.messagebody, message.fromid,message.toid,message.messageid,message.datetime 
FROM message,users 
WHERE message.fromid = users.memberid AND message.toid = '$id' AND recieverdeleted='0' )INTERMEDIATE_TABLE ORDER BY datetime DESC

我的语法可能有问题,因为很久以前我已经完成了sql代码,但你应该尝试类似这样的东西。

答案 2 :(得分:0)

试试这个工作

SELECT m1.* 
  FROM table_name m1 
  INNER JOIN (SELECT MAX(senddate) AS senddate, 
                     IF(member_id2 = 3, member_id1, member_id2 ) AS user 
                FROM table_name 
               WHERE (member_id1 = 3 AND delete1=0) OR 
                     (member_id2 = 3 AND delete2=0) 
              GROUP BY user) m2 
         ON m1.senddate = m2.senddate AND 
           (m1.member_id1 = m2.user OR m1.member_id2 = m2.user) 
     WHERE (member_id1 = 3 AND delete1=0) OR 
           (member_id2 = 3 AND delete2=0) 
   ORDER BY m1.senddate DESC

答案 3 :(得分:-1)

试试这个::

   SELECT users.memberid,users.username,users.profileimage,users.gender,message.messagebody, message.fromid,message.toid,message.messageid 

FROM message inner join users on (message.fromid = users.memberid)
where  message.toid = '$id' AND recieverdeleted='0' 
ORDER BY message_datetime DESC limit 1