mySQL Group的成员名称

时间:2016-09-14 21:54:56

标签: php mysql

我正在使用此查询来获取向用户发送消息的用户列表或用户消息的用户列表。

SELECT messages.* 
FROM (
    SELECT MAX(lastseen) AS lastseen 
    FROM messages
    WHERE '".$user."' IN (from,to)
    GROUP BY IF ('".$user."' = from,to,from)
) AS latest
LEFT JOIN messages 
USING(lastseen) 
ORDER BY lastseen desc,(read='no' and to='".$user."') limit 10

但是,它可以显示一些用户两次。

enter image description here

仅向用户展示一次的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

我认为这就是你所追求的目标。

SELECT messages.* 
  FROM 
  (SELECT MAX(lastseen) AS lastseen,IF ('Tom' = `from`,`to`,`from`) as otheruser FROM messages
    WHERE 'Tom' IN (`from`,`to`) GROUP BY otheruser
   )
AS latest INNER JOIN messages ON latest.lastseen = messages.lastseen
                             AND (('Tom' = messages.from AND latest.otheruser = messages.to)
                                 OR
                                 ('Tom' = messages.to AND latest.otheruser = messages.from))
ORDER BY messages.lastseen
DESC,`read`='no' limit 10

直接替换汤姆'使用您的变量

这将返回发送给“汤姆”的最新10位用户。或者'汤姆'发信息给。