1

我有两个 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

现在返回的是everymessage的所有信息,而不考虑formid(发件人的ID)问题是,我只想显示每个来自ID的最新消息..有点像Facebook如何只向您显示最新消息那个朋友 x 发给了你,而不是所有的消息。在用户点击他朋友的最新消息后,我将努力显示所有消息。谢谢

4

4 回答 4

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;
于 2013-04-06T11:22:48.913 回答
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 代码,但你应该尝试一些非常相似的东西。

于 2012-07-01T17:16:21.957 回答
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
于 2013-04-06T10:48:35.503 回答
-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
于 2012-07-01T17:21:49.903 回答