如何获取我在邮件系统中与之交互的用户列表

时间:2015-03-02 20:56:52

标签: mysql

我正在尝试获取我在邮件系统中与之交互过的用户列表:

TABLE:

messages: id, sender_id, recipient_id, message, date

SQL:

SELECT * FROM `messages` 
WHERE 
(`sender_id` = :user_id OR `recipient_id` = :user_id)
GROUP BY `sender_id`, `recipient_id`
ORDER by `date` DESC

这为我提供了多行,发件人/收件人ID不匹配

我认为导致它的GROUP BY不确定如何解决它

编辑:我每次互动只需要1行(因此GROUP BY

1 个答案:

答案 0 :(得分:2)

GROUP BY会将所有行与sender_idrecipient_id组合在一起。使用UNION将两组合并为一组结果:

SELECT correspondent, MAX(date) AS last_date
FROM (
    SELECT sender_id as correspondent, date
    FROM messages
    WHERE recipient_id = :user_id

    UNION ALL

    SELECT recipient_id as correspondent, date
    FROM messages
    WHERE send_id = :user_id) x
GROUP BY correspondent
ORDER BY last_date DESC