我正在尝试获取我在邮件系统中与之交互过的用户列表:
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
)
答案 0 :(得分:2)
GROUP BY
会将所有行与sender_id
和recipient_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