mySQL Group(只显示一个成员一次)

时间:2016-09-15 12:17:09

标签: 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 DISTINCT 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