我正在使用此查询来获取向用户发送消息的用户列表或用户消息的用户列表。
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
但是,它可以显示一些用户两次。
仅向用户展示一次的正确方法是什么?
答案 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位用户。或者'汤姆'发信息给。